首页 > 解决方案 > 每天将 3 个随机帖子分配给一个类别

问题描述

我想创建一个日常功能的食谱。

因此,我想将 3 个具有自定义帖子类型“recipe”的 wordpress 帖子添加到“reciepe of the day”类别中。

我也想从预览日中删除当天的食谱。

我已经有几行代码,但我不知道如何在那里分配和取消分配类别。

TLDR:我的问题:我不知道如何为我的循环分配和取消分配类别。

add_action( 'wp', function () {
    if (! wp_next_scheduled ( 'mark_posts_as_featured_event' )) {
        wp_schedule_event(time(), 'daily', 'mark_posts_as_featured_event');
    }
} );

function mark_posts_as_featured_event_callback() {
    // if there are sticky posts in our CPT, unstick them
    $sticked_post_ids = get_option( 'sticky_posts' );
    if ( ! empty ) { 
        $old_featured_posts = get_posts( array(
            'post_type' => '<MY_POST_TYPE>',
            'fields' => 'ids',
            'post__in' => $sticked_post_ids,
        ) );

        foreach ( $old_featured_post_ids as $post_id ) {
            // unassign category
        }
    }

    // stick new posts
    // get_random_posts
    $new_featured_post_ids = get_posts( array(
        'post_type' => '<MY_POST_TYPE>',
        'posts_per_page' => 3,
        'orderby' => 'rand',
        'fields' => 'ids',
    ) );

    foreach ( $new_featured_post_ids as $post_id ) {
        // assign category
    } 
}
add_action( 'mark_posts_as_featured_event', 'mark_posts_as_featured_event_callback' );

标签: wordpresscustom-post-typecustom-taxonomy

解决方案


我认为你正在寻找

    wp_set_post_categories() 

功能。

https://developer.wordpress.org/reference/functions/wp_set_post_categories/

您可以添加当天的“每日食谱”类别。第二天运行一个函数,使用与上面相同的方法并将 bool 设置为“true”,然后添加 recipies 类别。

然后这将删除所有帖子类别并仅分配您给它的那些,即recepies。


推荐阅读