有没有办法自动更改最后 post 的 wordpress 类别

Is there a way to automaticly change wordpress category of last post

我在 wordpress 中有一个作品集。 我想要做的是最后 3 posted 投资组合 posts 他们有一个名为 last-gaming-news 的类别。另一个 post 不需要任何类别

有插件吗?或一些 php 代码。

您需要做的是:

  • 首先删除所有帖子的这个类别(因为我猜你想要这个类别最后三个帖子,对吧?)
  • select最近的三篇文章,给他们你想要的分类

我建议:

<?php
add_action( 'init', 'custom_function');

function custom_function(){
    $posts = get_posts([ 
          'post_type'        => 'portfolio'
            ]);

    foreach ($posts as $post){
        wp_remove_object_terms( $post->ID, 'last-gaming-news', 'types' );
    }

    $args = [ 'orderby'          => 'date',
          'order'            => 'DESC',
          'post_type'        => 'portfolio',
          'post_status'      => 'publish',
          'posts_per_page'   => 3 ];

    $latest3posts = get_posts($args);

    foreach( $latest3posts as $post ){
        wp_set_post_categories( $post->ID, 'last-gaming-news', 'types', true );
    }
}