I'm trying to display an image in a custom field on child category archive pages.
The current setup is:
<?php
$term_id = get_queried_object()->term_id;
$post_id = 'product_cat_'.$term_id;
$custom_field = get_field('brand_background', $post_id);
?>
<div id="brandHeader" class="brand-header-logo" style="background-image: url('<?php the_field('brand_background', $post_id); ?>');">
This obviously gets the 'background image' field from the category archive it's currently on.
If the category is a child category I want to be able to pull the 'background image' from the parent category. I've tried a few things but doesn't seem to be working - can anyone help?
You could use the get_ancestors
function to get the parent id
and use that id to get your field:
So let's say your categories looks like this:
-Parent (id = 24)
--Child (id = 42)
$term_id = get_queried_object()->term_id;
$term_ancestor_ids = get_ancestors($term_id, 'product_cat');
// if you do a print_r on $term_ancestor_ids
// you'll see this:
// Array ( [0] => 24 )
$post_id = 'product_cat_'.$term_ancestor_ids[0];
$custom_field = get_field('brand_background', $post_id);
Tested and works, let me know if you were able to get it to work too!