• Resolved oliveran

    (@oliveran)


    I use a couple of custom field in my posts.

    To expose the value in the post, I’ve created a simple shortcode function, for example this for a custom field called ‘sector’:

    add_shortcode('cf_sector', 'cf_sc_sector');
    function cf_sc_sector($atts=[], $content=null){
      global $post;
      return get_post_meta( $post_id=$post->ID, $key = 'sector', $single = true );
    }

    This works perfectly in the post, for example /test/test_post

    However, it does not work when I add the same short code inside the Post Template block within a Query Loop example /test_loop

    On further investigation it seems that the global variable $post is referencing the containing page, not the post inside the loop.

    Am I doing something wrong ??

    I’m new to WP and this forum so please send me to right location if this isn’t it, thanks.

    • This topic was modified 2 years, 6 months ago by bcworkz. Reason: code format fixed
    • This topic was modified 2 years, 6 months ago by Jan Dembowski.

    The page I need help with: [log in to see the link]

Viewing 5 replies - 1 through 5 (of 5 total)
  • You’re not doing anything wrong. What are you seing is the expected behaviour.

    If you want the shortcode to interact with a post in a secondary loop (or any other post outside of the standard loop), it’s worth passing that post in as part of the arguments and using that.

    As an example (not tested, could be very broken)…

    function cf_sc_sector($atts=[], $content=null){
      if (array_key_exists ('postid', $atts) {
        $post = get_post ($atts ['postid']);
      }
      else {
        global $post;
      }
      
      return get_post_meta( $post_id=$post->ID, $key = 'sector', $single = true );
    }
    Thread Starter oliveran

    (@oliveran)

    Thanks, I’ll give that a try. At least I know I’m not completely insane.

    Any follow up on this?

    Are you adding this into functions.php or somewhere else? I’m having a similar issue. Thanks!

    Thread Starter oliveran

    (@oliveran)

    Hi arealdadsdad,

    I tried it in functions.php.
    I never got it to work, but could never expose the ID of the post in the loop.
    in the end I organised my site differently.

    Andy

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Custom Field (via Shortcode) inside Query Loop block’ is closed to new replies.