WordPress.org

Ready to get started?Download WordPress

Forums

Simple code to insert custom field into shortcode. What is wrong? (5 posts)

  1. pates
    Member
    Posted 1 year ago #

    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.

  2. ianhaycox
    Member
    Posted 1 year ago #

    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.

  3. pates
    Member
    Posted 1 year ago #

    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.

  4. ianhaycox
    Member
    Posted 1 year ago #

    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.

  5. pates
    Member
    Posted 1 year ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.