Search code examples
phpwordpressreturnshortcodecustom-fields

Return value within function in Wordpress to display a custom field


I'm not sure I'm doing the right thing. Here's my problem:

function getCustomField() {
    global $wp_query;
    $postid = $wp_query->post->ID;
    echo '<p>'.get_post_meta($postid, 'blog_header', true).'</p>';
    wp_reset_query();

}

With this function I'm able to display my custom field pretty much everywhere in my template with wordpress when I call my function getCustomField like that:

<?php getCustomField(); ?>

But this is not quiet what I want to achieve. Ideally I want to return a value from this function to essentially do the same thing with a shortcode, so same thing but instead of echo the value I want to return the value and add at the very end:

add_shortcode('custom', 'getCustomField');

So I can call it in my theme in this way:

or within the loop just with the shortcode [custom].

It is not working of course, where is my mistake?

Last thing, in the remote case it will work should I return my value at the very end, something like this:

global $wp_query;
$postid = $wp_query->post->ID;
wp_reset_query();
return '<p>'.get_post_meta($postid, 'blog_header', true).'</p>';

Solution

  • In a shortcode you want to retrieve the post id like this:

    function getCustomField() {
    
        $post_id = get_the_ID();
        return '<p>'.get_post_meta( $post_id, 'blog_header', true ).'</p>';
    }
    add_shortcode( 'custom', 'getCustomField' );
    

    It might also be smart to check for a value from the get_post_meta() function. otherwise you will end up with empty paragraph tags. You can do that like this:

    function getCustomField() {
    
        $post_id = get_the_ID();
        $blog_header = get_post_meta( $post_id, 'blog_header', true );
    
        if( $blog_header ) {
    
            return '<p>'.$blog_header.'</p>';
    
        }else{
    
            return false;
        }
    }
    add_shortcode( 'custom', 'getCustomField' );