0

I am creating a function, for a shortcode that I will use directly in the post content (using [my_description_number] shortcode), and it works, but I do not manage to call (echo or print) a custom field value.

this will not print the custom field value, maybe you know how to make it work? just to print the value of custom field song_number when the shortcode will be called

many thanks

function wpb_description_shortcode( $atts ) : string { ob_start(); ?> <?php if (get_post_meta(get_the_ID(), 'song_number', true)) { ?> <?php echo get_post_meta($post->ID, 'song_number', true); ?><br/> <?php } else { ?> <?php } ?> <?php return ob_get_clean(); } // Register shortcode add_shortcode('my_description_number', 'wpb_description_shortcode');``` 
2
  • Are you calling this function within the loop? Commented Feb 6, 2022 at 0:46
  • I am calling it in the post content, through the shortcode, when adding a post in the WordPress admin Commented Feb 6, 2022 at 0:54

1 Answer 1

1

if you're not planning on adding much html there is no need to use ob_start just return the php:

function wpb_description_shortcode( ){ if (get_post_meta(get_the_ID(), 'song_number', true)) { return get_post_meta(get_the_ID(), 'song_number', true).'<br/>'; } else { return; } } // Register shortcode add_shortcode('my_description_number', 'wpb_description_shortcode'); 

I'm not sure what this data is, but it would be a good idea to sanitize it too for security.

If you're planning on adding more fields you could do it like this:

function wpb_description_shortcode( ){ $output = ''; if (get_post_meta(get_the_ID(), 'song_number', true)) { $output .= get_post_meta(get_the_ID(), 'song_number', true).'<br/>'; } if (get_post_meta(get_the_ID(), 'another_field', true)) { $output .= get_post_meta(get_the_ID(), 'another_field', true).'<br/>'; } //random html $output .= '<h3> cool html </h3>'; if (get_post_meta(get_the_ID(), 'even_another', true)) { $output .= get_post_meta(get_the_ID(), 'even_another.', true).'<br/>'; } return $output; } // Register shortcode add_shortcode('my_description_number', 'wpb_description_shortcode'); 
3
  • thanks! I am adding more html, and I'm also trying to add more than one custom fields there. I tried to adapt to your code, but when adding more custom fields it will give a fatal error. any way to add more than one custom field? and between them I have some html Commented Feb 6, 2022 at 1:29
  • I used echo and it worked, I could add more custom fields. so your answer solved it. much appreciated! Commented Feb 6, 2022 at 1:38
  • 1
    added other fields and a some random HTML @vyperlook Commented Feb 6, 2022 at 4:01

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.