计算类别中的帖子并从类别中自动删除

时间:2016-01-11 06:17:29

标签: php wordpress function

我的帖子分为两类。 (特色,新闻)。 我试图计算'特色'类别中的帖子,如果超过5我希望它删除6,7,8,... 只保留最新5 .. 到目前为止,我可以使用此代码计算它们

$category = get_category(830);
$count = $category->category_count;

if( $count > 5 ) {
    // stuff
}

但在if语句中如何获取项目6,7,8 ......?

我只想删除category_id 830中的“精选”类别,并保留其中列出的其他类别(新闻)。

我做了这个功能,但是当我使用它时我得到错误500。 你能救我吗?

$my_query = new WP_Query( 'category_name=featured' );
function countfeatures($my_query) {
$featurecount = 0;

    while ( $my_query->have_posts() ) : $my_query->the_post();
    $featurecount++;
    if ($featurecount > 5){  
    $pos = array_search( 'featured', $post_cats );
    unset( $post_cats[$pos] );
    wp_set_post_terms ($post_id, $post_cats, 'category');
    //wp_set_post_terms ($slide->ID, $post_cats, 'category');
    //do stuff 
    }
        endwhile;

    }
add_filter('pre_get_posts', 'countfeatures');

2 个答案:

答案 0 :(得分:0)

使用限制查询5和按主键排序降序,这样您将获得前五名最新记录

答案 1 :(得分:-1)

  

只需添加orderby和order参数即可   最新的5个特色类别的帖子。

    $args = array(
            'post_type' => 'post',
            'post_status'=> 'publish',
            'posts_per_page'=>5,
            'order'=>'DESC',
            'orderby'=>'ID',
            'tax_query' => array(
                array(
                    'taxonomy' => 'featured',
                    'field'    => 'term_id',
                    'terms'    => array(830),
                    'operator' => 'IN',
                ),
            ),
        );
        $query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
相关问题