我是说,有7000多个职位。有些人有私人空间,但有些人没有。我想大量添加一个自定义字段到那些不包含自定义字段并更新其值的字段中。
下面的插件代码已经创建,以更新所有帖子的元值。我只想把它添加到不包含元值的帖子中。我怎么能这么做?
'post', // Only get the posts
'post_status' => 'publish', // Only the posts that are published
'posts_per_page' => -1 // Get every post
);
$posts = get_posts($args);
foreach ( $posts as $post ) {
// Run a loop and update every meta data
update_post_meta( $post->ID, 'meta-key', 'meta_value' );
}
}
?>发布于 2021-03-18 21:09:56
您可以使用元数据_查询参数 (和查询不存在元键的所有帖子)将查询限制为只有具有或没有特定元值的帖子。
$query = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'your_meta_key',
'compare' => 'NOT EXISTS',
),
),
'no_found_rows' => true,
'fields' => 'ids',
));
if ( $query->posts ) {
array_walk(
$query->posts,
function($post_id, $index) {
update_post_meta( $post_id, 'your_meta_key', 'meta_value' );
}
);
}此外,取决于您的主机,您可能希望设置对posts_per_page的限制,并多次运行该脚本(可能吗?)而不是使用-1,因为对数千个帖子的查询可能会使站点崩溃,或者执行时间可能会耗尽。
https://wordpress.stackexchange.com/questions/384738
复制相似问题