Support Forum
Support › MB Custom Post Type › CPT, Custom Taxonomy with added image field: how do I get the image?Resolved
I have a CPT, where I have added a Taxonomy Advanced field with the id "art_author". The field is connected to the taxonomy "author".
For this taxonomy I have added a custom Image Advanced field with the id "tax_image". So for each term I can add an author image.
In the template for the CPT (actually a Bricks Builder template) I can easily get the author name using:
$terms = rwmb_meta( 'art_author' );
But how do I get the author image(s) in the CPT template? When I test with your suggested code:
// Displaying uploaded images:
$images = rwmb_meta( 'tax_image', [ 'object_type' => 'term', 'size' => 'thumbnail' ], get_queried_object_id() );
?>
<h3>Uploaded images</h3>
<ul>
<?php foreach ( $images as $image ) : ?>
<li><img src="<?= $image['url']; ?>"></li>
<?php endforeach ?>
</ul>
I just get the error message:
Warning: foreach() argument must be of type array|object, string given ...
What do I miss?
Hello,
If you use this code get_queried_object_id()
in the CPT template, it will return the current post ID, not the term ID. So you need to pass the term ID to the helper function rwmb_meta()
.
If the option multiple
is not set for the field, you can use the variable $terms
to pass to the third parameter. For example:
$terms = rwmb_meta( 'art_author' );
$images = rwmb_meta( 'tax_image', [ 'object_type' => 'term', 'size' => 'thumbnail' ], $terms );
Please read more in the documentation https://docs.metabox.io/fields/taxonomy-advanced/#data
https://docs.metabox.io/extensions/mb-term-meta/#data
Thanks!
If I change to
$images = rwmb_meta( 'tax_image', [ 'object_type' => 'term', 'size' => 'thumbnail' ], $terms );
it still does not produce anything (and no error message). If I do print_r($images); it prints "1".
Hello,
Can you please print out the variable $terms
to see what value it is stored?
print_r($terms) gives only the standard WP content of the "author" taxonomy:
[0] => WP_Term Object
(
[term_id] => 15
[name] => John Doe
[slug] => john-doe
[term_group] => 0
[term_taxonomy_id] => 15
[taxonomy] => author
[description] => Teacher
[parent] => 0
[count] => 0
[filter] => raw
[term_order] => 1
)
)
Where is my MB custom field "tax_image" connected to my taxonomy "author"?
Hello,
It's an array of term objects so you need to use a loop to get each term ID. In this case, you can use the sample code to get the author images:
$images = rwmb_meta( 'tax_image', [ 'object_type' => 'term', 'size' => 'thumbnail' ], $terms[0]->term_id );
Thanks! That did the trick!
/Bengt