Wordpress Custom Fields from Category on Product Page

Joined
Apr 7, 2016
Messages
315
Likes
216
Degree
1
I'm trying to show a custom field from a product category on it's child product pages using the Advanced Custom Fields wordpress plugin.

Getting values from another page
https://www.advancedcustomfields.com/resources/code-examples/

Their code example has a variable $other_page = 12; I'm not totally sure what this is. I'm guessing this is the parent category ID.

I'm trying to get the parent subcategory ID with the following:

global $post;
$prod_terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($prod_terms as $prod_term) {

// gets product cat id
$product_cat_id = $prod_term->term_id;
}

So far no luck. Any ideas on what I'm doing wrong?
 
Their code example has a variable $other_page = 12; I'm not totally sure what this is. I'm guessing this is the parent category ID.

Yeah, it's an ID.

So are you saying you have...

Category -> Post / Page​

And you want a field from the category to show on those posts?

Or are you saying...

Category -> Subcategory -> Post / Page
It's not clear what your hierarchy and architecture is here, but it'll matter in how you generalize the code to fetch the ID you need and have it work across all instances.
 
I have Woocommerce Category -> Woocommerce Subcategory -> Product Page.

My custom field is assigned to the Woocommerce Subcategory and I want to show it on the Product Page
 
Have you tried something like...

Code:
<?php
$cat = get_queried_object();
$catID = $cat->term_id;
echo $catID;
?>

Echoing on the last line just to check if its working. I've not used WooCommerce so I'm not entirely sure of the jargon... that might get it done though.

You might even be able to skip some of that and go straight to...

Code:
$catID = get_queried_object_id();

By the way, have you tried to explicitly state the Subcategory ID in that chunk of code in your first post to verify it does what you want?
 
I didn't realize until now that you can see the IDs of the categories and posts in the url in the admin section. So, the code I posted does grab the ID of the subcategory. I explicitly posted the ID number into the ACF code example with no result. I'll keep digging.
 
Update: I got it! In order to show an ACF custom field from anything other than a post or a page, you need the id and the taxonomy name. Example)
Code:
$variable = get_field('field_name', 'product-cat_23');

The following code is what I ended up using to display custom fields from a different taxonomy:
Code:
global $post;
$prod_terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($prod_terms as $prod_term) {

    // gets product cat id
    $product_cat_id = $prod_term->term_id;
}

$woocommerce_product_cat = 'product_cat_' . $product_cat_id;

$variable = get_field('field_name', $woocommerce_product_cat);
echo $variable;

I appreciate your help Ryuzaki!
 
Last edited:
Back