简体   繁体   中英

get_post_meta does not work in a WP_Query loop (returns empty array)

This issue has had me stumped today. This code pretty much worked before today, albeit as top-level code in functions.php rather than as an admin page.

What this code does:

  • Create an admin page. dothing() is the function that renders it.
  • If you have a specific username, then start looping through the posts and printing out their metadata.

Oddity: Before any of the wp query stuff, if you try to print_r the get_post_meta of one of your posts (copy and paste the ID as an integer value manually), it will fetch the post meta for that one particular post.

Inside of the loop, what get_post_meta returns is an empty array.

function dothing(){
    $username = wp_get_current_user()->user_login;

    if ( $username == 'foobar' )
    {
        echo '<div style="color: blue;max-width: 500px; margin: 0 auto;">';

        $args = array(
            'post_type' => 'post',
            'posts_per_page' => -1,
        );

        $my_query = new WP_Query( $args );

        while ( $my_query->have_posts() ) {
            $my_query->the_post();
            $myid = get_the_ID();
            echo 'the ID ' . $myid . ' has the meta fields: ';
            print_r( get_post_meta($myid) );
            echo '<br><br>';
        }

        wp_reset_postdata();

        echo '</div>';
    }
}

function my_admin_menu() {
    add_menu_page( 'DoTHING', 'Dothing', 'manage_options', 'dothing', 'dothing', 'dashicons-tickets', 6  );
}

add_action( 'admin_menu', 'my_admin_menu' );

Try using get_post_custom() instead of get_post_meta() . get_post_meta() is designed around fetching an individual key=>value pair, but defaults to an empty string which should return all fields (though I've found it to be inconsistent). I've found get_post_custom() to be more reliable when I need to sift through all of the meta fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM