获取表参数并保存为元值

时间:2019-06-19 作者:Juca Camarada

我想得到number_1number_2 并保存在meta_value 在表中wp_postmeta. 我该怎么做呢?这个id_help_i$post-> ID. 表的某些idwp_table_help_i 没有参数number_1number_2 那些没有的我想添加一个示例值99999

抱歉英语不好

 function update_my_metadata() {


            $args = array(
                \'post_type\' => \'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) {
                global $wpdb;
                $meta_value = $wpdb->get_var($wpdb->prepare("SELECT Number_1 + Number_2 FROM wp_table_help_i WHERE id_help_i = \'$post->ID\'", $id));
                // Run a loop and update every meta data
                update_post_meta($post->ID, \'meta_key\', $meta_value);
            }
        }

            // Hook into init action and run our function
            add_action(\'init\', \'update_my_metadata\');

1 个回复
最合适的回答,由SO网友:MikeNGarrett 整理而成

请记住,如果将此保留在init操作上,则每次加载页面时都会发生这种情况。如果只希望此操作发生一次或在另一个操作期间发生,则需要更改此操作。

如果您尝试在过多的帖子上执行此操作,也会超时。

function update_my_metadata() {

    $args = array(
        \'post_type\'      => \'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 ) {
            global $wpdb;
            $number_one = $wpdb->get_var( $wpdb->prepare( "SELECT Number_1 FROM {$wpdb->prefix}table_help_i WHERE id_help_i = %d", $post->ID ) );
            $number_two = $wpdb->get_var( $wpdb->prepare( "SELECT Number_2 FROM {$wpdb->prefix}table_help_i WHERE id_help_i = %d", $post->ID ) );
        if ( ! empty( $number_one ) ) {
            update_post_meta( $post->ID, \'your_meta_key_name\', $number_one );
        }
        if ( ! empty( $number_two ) ) {
            update_post_meta( $post->ID, \'your_meta_key_name\', $number_two  );
        }
    }
}
add_action(\'init\', \'update_my_metadata\');