我如何限制每个类别创建的帖子数量?

时间:2017-06-07 作者:user1619177

如何限制每个类别创建的帖子数量?然后删除最旧的帖子并保存它?

我想这样做:

 add_action("load-post-new.php","limit_post_per_category");
  function limit_post_per_category(){
   $category = get_current_category(); //--not sure about this function....//
   if ($category == "category1") { 

    $category_post_count = count_posts($category);
    if($category_post_count>=10){
        delete the oldest post in the category;
        save post;
  }
 }
}

1 个回复
最合适的回答,由SO网友:hwl 整理而成

我会把它挂上publish_post, 这样你就不会弄乱草稿等了。

你需要考虑多个类别,计算每个类别中的帖子数量,删除超过10个的帖子。

也许这样的事情会让你走上正确的方向。可能需要一些调整,大部分未经测试。

function on_post_publish( $ID, $post ) {

    $cat = get_the_category( $ID ); //returns array of categories

    foreach ($cat as $c) {    //doing the rest for each cat in array
        $args = array(
                    \'orderby\'  => \'post_date\',   //using the post date to order them
                    \'order\'     => \'ASC\',       // putting oldest at first key
                    \'cat\'       => $c,          // only of the current cat
                    \'posts_per_page\'  => -1,   //give us all of them
                    \'fields\' => \'ids\'         //only give us ids, we dont want whole objects
            );
       $query = new WP_Query( $args );

       $count = $query->post_count;         //get the WP_Queries post_count object value

       if ($count > 10) {                         // if that value is more than 10
            $id_to_delete = $query->posts[0];    //get oldest post from query
            wp_delete_post( $id_to_delete );    //delete it
       }


    }
    wp_reset_postdata(); //resetting to main query just in case


}

add_action(  \'publish_post\',  \'on_post_publish\', 10, 2 );

结束

相关推荐

Query total number of posts

使用搜索过滤器插件。我使用获取数据库中存在的帖子总数 $wp_query->found_posts 但是,当用户过滤页面上的结果时,该数字会根据过滤器上显示的帖子数量而变化。我怎样才能得到不管用户过滤什么都不会改变的静态帖子总数?更新:这是我的完整模板代码。我尝试了下面的答案,但无法使用我的模板。有什么想法吗?if ( $query->have_posts() ) { ?> <ul id=\"florefs\"> &l