如果我手动操作,有一百个帖子来更新postmeta。我试图找到一种方法来插入基于post_type
和类别的新postmeta。我试试这个:
$args = [
'post_type' => 'post',
'category_name' => 'category'
];
$query = new WP_Query($args);
if( $query->have_posts() ) {
while ( $query->have_posts() ) {
add_post_meta($query->post->ID, '_meta_key', meta_value, true);
add_post_meta($query->post->ID, '_meta_key2', meta_value2, true);
add_post_meta($query->post->ID, '_meta_key3', meta_value3, true);
add_post_meta($query->post->ID, '_meta_key4', meta_value4, true);
add_post_meta($query->post->ID, '_meta_key5', meta_value5, true);
}
}
它不起作用。无论如何要实现吗?
好的,我在这里找到答案Trigger action when new post is insert in wordpress
发布帖子或页面或自定义帖子时添加元值。
function save_post_meta( $post_id, $post, $update ) {
$post_type = get_post_type($post_id);
if ( "your post name" != $post_type ){ return;}
update_post_meta( $post_id, 'meta_key', 'value');
}
add_action( 'save_post', 'save_post_meta', 10, 3 );
使用update_post_meta
函数更新post元值。
$args = [
'post_type' => 'post',
'category_name' => 'category'
];
$query = new WP_Query($args);
if( $query->have_posts() ) {
$query->the_post();
while ( $query->have_posts() ) {
update_post_meta($query->post->ID, '_meta_key', meta_value, true);
update_post_meta($query->post->ID, '_meta_key2', meta_value2, true);
update_post_meta($query->post->ID, '_meta_key3', meta_value3, true);
update_post_meta($query->post->ID, '_meta_key4', meta_value4, true);
update_post_meta($query->post->ID, '_meta_key5', meta_value5, true);
}
}