Support » Fixing WordPress » Simple code to insert custom field into shortcode. What is wrong?

  • function companylink( $atts, $content = null ) {
    $link = echo get_post_meta($post->ID, 'companylink', true);
    return $link;
    }
    
    add_shortcode('companylink', 'companylink');

    Any help here would be hugely appreciated. I’m just trying to echo a custom field into a shortcode.

    The shortcode will be [companylink] and it should return $link which is just echoing the custom field.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Where is $post defined ?

    I suspect you’ll need a global $post in your function.

    When testing define WP_DEBUG to true in wp-config.php to display PHP notices, and look in the server error log file for clues.

    Ian.

    Thread Starter pates

    (@pates)

    Thanks Ian, I’m assuming you meant this?

    global $post;
    function companylink( $atts, $content = null ) {
    $link = <strong>echo </strong>get_post_meta($post->ID, 'companylink', true);
    return $link;
    }
    
    add_shortcode('companylink', 'companylink');

    Unfortunately the code is still broken. It appears to be the ‘echo’ that is breaking it.

    function companylink( $atts, $content = null ) {
    global $post;
    $link = get_post_meta($post->ID, 'companylink', true);
    return $link;
    }

    No need for the echo – the shortcode handler must return the value.

    Thread Starter pates

    (@pates)

    Fantastic! I’m not sure of the logic to this code but it’s working great. Thank you very much Ian.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Simple code to insert custom field into shortcode. What is wrong?’ is closed to new replies.