skip to Main Content

I want to display advanced custom fields from my Product categorie on the product page that it is in.

so lets say I am on Home > category1 > category2 > Product

Category 2 is always a brand so I made a custom field where the value is "YES" if the product is a brand an "NO" if it isn’t a brand.

This displays the category AFC but not the last one so not category2 but category1 code

<?php
function get_current_product_category1(){

        global $post;

       $terms = get_the_terms( $post->ID, 'product_cat' );

        $nterms = get_the_terms( $post->ID, 'product_tag'  );

        foreach ($terms  as $term  ) {                    

            $product_cat_id = $term->term_id;              

            // $product_cat_name = $term->name;      
            
            $product_cat_name = get_field('merk_header_afbeelding', $term);
            

            break;

        }

       return $product_cat_name['url'];


}
add_shortcode ('categorie_acf2', 'get_current_product_category1');
?>

2

Answers


  1. Chosen as BEST ANSWER

    So I made a custom field that makes it a category2 or category1 and I filter on that so I only get back the Category2 items.

    function get_current_product_category5() {
        global $post;
    
        $terms  = get_the_terms( $post->ID, 'product_cat' );
        $nterms = get_the_terms( $post->ID, 'product_tag' );
    
        foreach ( $terms  as $term ) {
            $product_cat_id   = $term->term_id;
    
            $product_cat_name = get_field( 'is_is_deze_categorie_een_merk', $term );
    
            // check if product AFC is ja
            if ( $product_cat_name === 'ja' ) {
                $product_cat_name2 = get_field( 'merk_header_afbeelding', $term );
            }
        }
    
        return $product_cat_name2['url'];
    }
    add_shortcode( 'categorie_acf3', 'get_current_product_category5' );
    

  2. You have a break inside the for loop. Try without the break.

    EDIT: Adding the code snippet to print the link to the category with "brand" custom field set to "Yes".

    This will print only the first category with brand "Yes". If there are more of them, then you should concatenate all of them into one string.

    function get_current_product_category5(){
    
        global $post;
    
        $terms = get_the_terms( $post->ID, 'product_cat' );
    
        foreach ($terms  as $term  ) {
    
            $is_brand = get_field('is_brand', $term);
            if($is_brand == "Yes")
            {
                return '<a href="' . esc_url( get_term_link( $term ) ) . '">'.$term->name.'</a>';
            }
        }
    }
    add_shortcode ('categorie_acf3', 'get_current_product_category5');
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search