I created a loop for logged-in-users-only which works perfectly for all data except for meta keys. I'd like to be able to also extract meta keys but had no luck so far.

This is my loop (based on this post):

<?php add_shortcode( 'current-userposts' , 'show_userposts' );
function show_userposts(){
$user_id = get_current_user_id();
$loop = new WP_Query( array( 'post_type' => 'photo-spot', 'author' => $user_id ) ); 
if ( $loop->have_posts() ) {    
<form class="pps-results"><?php
        while ( $loop->have_posts() ) : $loop->the_post(); ?>
                    <legend class="title-block">
                        <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
                    <div class="category-block">
                        <?php $categories = get_the_category(); 
                        if ( ! empty( $categories ) ) {
                            echo esc_html( $categories[0]->name );   
                    if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
                        ?><div class="image-block"><?php
                    the_post_thumbnail( 'thumbnail' );
                    <div class="address-block">
                        <?php echo get_post_meta($post->ID, '_cf_address', true); ?>
            <div class="clear"></div>     
<?php endwhile; ?>
} ?>

The function is called via a shortcode

When I use the exact same loop in a search.php template the custom value ('_cf_address') shows up perfectly but somehow not with the shortcode...

Any idea what might be going wrong?

PS> The preview screen doesn't show my html code - I hope it show up alright.

  • @pieter-goosen How did you do that? I struggled getting the code show correctly... – Chris Homan Jan 25 '16 at 18:07
  • When you add code in the editor, highlight all your code and click on the {} sign above the editor. This indent each line of code with 4 spaces. Alterbnatively, indent each line with 4 spaces ;-) – Pieter Goosen Jan 25 '16 at 18:09
  • Apart from not invoking the $post global, a shortcode should never ever echo output, output should be returned – Pieter Goosen Jan 25 '16 at 18:10
  • @ChrisHoman Maybe just me but </div></div></fieldset> has one closing div to much? (has nothing to do with the rest of the code but thought it would be better to mention (only when I am correct ofcourse)). – Charles Jan 25 '16 at 18:12

There is no $post var local to your function, you need to use global $post first, or get_the_ID().

get_post_meta( get_the_ID(), '_cf_address', true );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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