Issues getting post id in WP_Query
-
I am using WP_Query to pull a specific category of posts and trying to pull an image for each one where there is a custom field set.
This is added in my header.php for a feature at the very top of the site.
Everything works, except for pulling the custom field. It renders as blank which doesn’t let the image load.
<?php // Find the specific category $topcat = get_categories('parent=26&hide_empty'); $mycat = $topcat[0]->cat_ID; // The Query $the_query = new WP_Query('cat='.$mycat); // The Loop while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <a href="<?php the_permalink() ?>" rel="bookmark"> <img src="<?php echo get_post_meta( $post->ID, 'top_slider', true) ?>" alt="<?php the_title() ?>" /> </a> <?php endwhile; // Reset Post Data wp_reset_postdata(); ?>Any help would be amazing! Thanks.
-
bump… any suggestions?
That looks alright to me (the post ID that is). Are you sure that category has any posts with a custom field “top_slider”? Try quering posts with a custom field ‘top_slider’:
$the_query = new WP_Query('cat='.$mycat.'&meta_key=top_slider');Unfortunately, I know that the custom field WAS working. It was working a few days ago. We updated a plugin which conflicted with the other way we had it coded and this was the alternative. For some reason the post ID just won’t pull.
keesiemeijer, I will give that a shot, but I think I’ve already tried that as well.
Any other guidance would be great.
Try echoing the ID inside the loop for testing:
<?php echo "the post ID=".$post->ID; ?>I did tried these two and neither of them would work:
<?php echo $post->ID; ?><?php echo $the_query->post->ID; ?>Why would it not work?
Alright, I was able to get it to pull the ID, just not in this line:
<?php echo get_post_meta( $post->ID, ‘top_slider’, true) ?>
Here is what I have at this point:
<?php global $post; // The Query $topcat = get_categories('parent=26&hide_empty'); $mycat = $topcat[0]->cat_ID; $the_query = new WP_Query('cat='.$mycat); // The Loop while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <a>" rel="bookmark"> <?php echo $post->ID; ?> <img src="<?php echo get_post_meta( $post->ID, 'top_slider', true) ?>" alt="<?php the_title() ?>" /> </a> <?php endwhile; // Reset Post Data wp_reset_postdata(); ?>Any help to get to the next step would be great.
That probably means the (category) post you’re querying doesn’t have a custom field “top_slider”. Look at the post ID’s in your wp-admin and see if they have the “top_slider” custom field set.
I got it! Thank you so much.
You were correct. It turns out that it was not pulling the right category and the one it had did not have the custom field. I missed your recommendation above of adding in the “key” into the query and that fixed the issue, in addition to these other revisions.
Thanks again!
The topic ‘Issues getting post id in WP_Query’ is closed to new replies.