wordpress - 每天将 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' );
解决方案
我认为你正在寻找
wp_set_post_categories()
功能。
https://developer.wordpress.org/reference/functions/wp_set_post_categories/
您可以添加当天的“每日食谱”类别。第二天运行一个函数,使用与上面相同的方法并将 bool 设置为“true”,然后添加 recipies 类别。
然后这将删除所有帖子类别并仅分配您给它的那些,即recepies。
推荐阅读
- javascript - 如何在 JavaScript 中创建构造函数(module.exports)
- arrays - 你能在 C 语言的另一个结构中创建一个结构数组吗?
- reactjs - 使用 Firebase Admin SDK 验证 ID 令牌
- wordpress - Wordpress footer_wp 问题重复内容
- django - 消息:新应用程序对象缺少必需的属性
- lua - 以编程方式创建局部变量(在 Lua 中)
- angularjs - 使用 JWT 令牌和 URL 中的 ID 调用 API
- bash - 我可以在 shell 脚本中暂时停止“tee”吗?
- google-apps-script - 如何在 Google 表格中查询一堆 CSV 文件?
- javascript - 打字稿错误 TS2583 找不到名称“设置”