I am building a WordPress theme and am onto displaying the custom fields of a custom post type. Instead of writing this a bunch of times:
<?php if(get_post_meta($post->ID, 'custom_item', true)){ echo $post_meta_data['custom_item'][0]; } ?>
Can’t I write a function to shorten this process? Something where I would pass it a variable and it can get plugged into the function. This is what I have so far with no luck:
<?php
function display_meta($custom_meta) {
if(get_post_meta($post->ID, $custom_meta, true)){ echo $post_meta_data[$custom_meta][0]; }}
?>
And then I want to be able to do something like this for each field:
<?php echo display_meta('custom_item') ?>
I am still relatively new to PHP and this is my first time trying to write a function like this. Any help is greatly appreciated!
looks like you need to pass $post and $post_meta_data to the function as well.
and you’re attempting (incorrectly) to do an echo twice. Something like this would work better
You should do some simple php tutorials and learn about functions and scoping tho.