WordPress.org

Support

Support » How-To and Troubleshooting » Simple code to insert custom field into shortcode. What is wrong?

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)
  • ianhaycox
    Member

    @ianhaycox

    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.

    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.

    ianhaycox
    Member

    @ianhaycox

    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.

    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.