php - get_post_meta does not work in a WP_Query loop (returns empty array)
Get the solution ↓↓↓This issue has had me stumped today. This code pretty much worked before today, albeit as top-level code infunctions.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, whatget_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' );
Answer
Solution:
Try using instead of
.
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 foundget_post_custom()
to be more reliable when I need to sift through all of the meta fields.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: a non well formed numeric value encountered
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.