Support » Developing with WordPress » How to set a taxonomy term meta field to a PHP variable

  • marv2

    (@marv2)



    Hi,
    I have a custom term meta field in wordpressthat I created and I currently use this code to display it:

    <?php $terms = get_the_terms($post->ID, 'camera');
    foreach ($terms as $term) {
    $term_id = $term->term_id;
    echo get_term_meta( $term_id, 'model', true );
    }?>

    However, I need to display this meta data multiple times in a few pages. I tried creating a global variable, but I am having no luck.

    This is what I tried:

    I put this in my functions.php:

    $camera = <"?php $terms = get_the_terms($post->ID, 'camera');
             foreach ($terms as $term) {
             $term_id = $term->term_id;
             echo get_term_meta( $term_id, 'model', true );
             }?">

    And then I put this in my template file:

    <p><?php global $camera;echo $camera;?><p/>
    But it is not working.

    Any ideas? Thanks!

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Jan Dembowski

    (@jdembowski)

    Brute Squad and Volunteer Moderator

    Moved to Developing with WordPress.

    create a function in your functions.php, like

    function printCameraModels()
    {
    $terms = get_the_terms($post->ID, 'camera');
             foreach ($terms as $term) {
             $term_id = $term->term_id;
             echo get_term_meta( $term_id, 'model', true );
             }
    }

    then simply call it from your template:
    <p><?php if(function_exists('printCameraModels') { printCameraModels(); } ?></p>

    Thanks for your reply. Is there any way to get a variable as such $printcameramodels instead of printCameraModels()? The reason I am asking is because one of my term meta fields has a link to an audio file, but when I use the wordpress audio shortcode with the printCameraModels() type variable, it doesn’t load the audio file. Thanks!

    Moderator bcworkz

    (@bcworkz)

    The reason your global did not work is probably because $camera was not declared global when it is assigned a value in functions.php. You can make something like that work with a global variable, but it’s a poor solution. You can have the printCameraModels() simply output what the audio shortcode would have output. Change the echo line to this version:
    echo do_shortcode('[audio src="' . get_term_meta( $term_id, 'model', true ) . '"]');

    I’m assuming the ‘model’ meta data you are getting are valid audio file references.

    Thanks!

Viewing 5 replies - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.