0

I want to get number_1 and number_2 and save in meta_value in table wp_postmeta. How do I do the same? The id_help_i and the same of the $post-> ID. Some id of the table wp_table_help_i does not have the parameters number_1 and number_2 the ones that do not have I would like to add an example value 99999 from already thank you

sorry bad english

 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 Answer 1

0

Keep in mind that if you leave this on the init action, this will occur on every page load. If you only want this to occur once or during another action, you'll need to change this.

This will also timeout if you try to execute this on too many posts.

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');
3
  • Thank you very much works. Know how I add a number to the $post-> ID not found in table_help_i ? Jun 19, 2019 at 20:05
  • para a 'your_meta_key_name' 1 number for all not found Jun 19, 2019 at 20:07
  • Thanks a lot I solved Jun 19, 2019 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.