如何在已发布的帖子上插入新隐藏的postmeta? WordPress的

问题描述 投票:0回答:2

如果我手动操作,有一百个帖子来更新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

wordpress insert-update
2个回答
0
投票

发布帖子或页面或自定义帖子时添加元值。

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 );

0
投票

使用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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.