每天为一个类别分配3个随机帖子

问题描述 投票:1回答:1

我想创建当天功能的食谱。

因此,我想将自定义帖子类型“食谱”的3个wordpress帖子添加到“当天的重播”类别中。

此外,我想删除前一天的食谱。

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

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' );
wordpress custom-post-type custom-taxonomy
1个回答
0
投票

我想你在寻找

    wp_set_post_categories() 

功能。

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

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

然后,这将删除所有帖子类别,并仅分配您提供的类别,即收据。

© www.soinside.com 2019 - 2024. All rights reserved.