简体   繁体   中英

Get relevant sub-category associated with the current product from parent category in WooCommerce

This is not meant to be a duplicate question, however, it seems that the wordpress.stackexchange forum is quiet on this one... Im hoping someone might help!

The following link of mine refers: Get only relevant sub-category of category...

I am busy with a music site. The scenario is the following:

  1. A song(WooCommerce product), has a category of "Rock" Rock is a sub-category of "Genre".
  2. The Genre category has a number of different sub-categories (Rock, Pop, Classical, etc).
  3. These categories were setup while importing products into WooCommerce and my Categories string in my initial import CSV looks like this (I'm using dummy data for development purposes):

Genre, Genre > Rock, Artist, Artist > Abigail Jay > Hulking Depend Weigh, Album > Hulking Depend Weigh, Year, Year > 2014

In the above example Rock is a sub-category of Genre.

With the following code I get all the sub-categories listed under "Genre":

global $product;
$terms = get_the_terms($product->get_id(), 'product_cat');
foreach($terms as $term)
{
    if($term->slug == "genre")
    {
        $_id = $term->term_id;
        $_s = $term->slug;
        $_ar = array('parent' => $_id);
        $assoc_categories = get_terms('product_cat', $_ar);
    }
}

This is however not correct. What I am trying to do (and not winning with) is to get hold of the relevant sub-category(for example Rock) associated with the current product via php. In other words I need to look which sub-category of Genre is associated with the product.

I am probably missing something small, however this has kept me busy for quite a while now... any help would be greatly appreciated!


EDIT:

Ok, I have come up with a bit of a round-about way to get what I need and have updated my code as follows:

global $product;
$terms = get_the_terms($product->get_id(), 'product_cat');
$_x = array();
foreach($terms as $term)
{
    if($term->slug == "genre")
    {
        $_id = $term->term_id;
        $_s = $term->slug;
        $_ar = array('parent' => $_id);
        $assoc_categories = get_terms('product_cat', $_ar);
        
        foreach(get_terms('product_cat', $_ar) as $_gt)
        {
            $genre_dict[] = $_gt->name;
        }
    }
    if(in_array($term->name, $genre_dict))
    {
        echo($term->name);
    }
}

A short explanation of the above :

  1. I create an array named $genre_dict containing all the sub-categories contained within the category Genre.
  2. I then compare $term->name with each entry in $genre_dict and if a match is found, I output $term->name .

Is there perhaps a better way of achieving the same result?

Ok, I have come up with a bit of a round-about way to get what I need and have updated my code as follows:

global $product;
$terms = get_the_terms($product->get_id(), 'product_cat');
$_x = array();
foreach($terms as $term)
{
    if($term->slug == "genre")
    {
        $_id = $term->term_id;
        $_s = $term->slug;
        $_ar = array('parent' => $_id);
        $assoc_categories = get_terms('product_cat', $_ar);
        
        foreach(get_terms('product_cat', $_ar) as $_gt)
        {
            $genre_dict[] = $_gt->name;
        }
    }
    if(in_array($term->name, $genre_dict))
    {
        echo($term->name);
    }
}

A short explanation of the above :

  1. I create an array named $genre_dict containing all the sub-categories contained within the category Genre.
  2. I then compare $term->name with each entry in $genre_dict and if a match is found, I output $term->name .

EDIT

I have created a more comprehensive bit of code builds an array containing the following:

  • Artist Name, ID, Slug >
    • Each Albums Name, ID, Slug, Year, Genre >
      • Each Songs Name, ID, Slug, SKU, Link to a preview of the Track
if((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443)
{
    $GLOBALS['base_href'] = 'https://'.$_SERVER['SERVER_NAME'].'/';
}
else
{
    $GLOBALS['base_href'] = 'http://'.$_SERVER['SERVER_NAME'].'/';
} // END OF: if((!empty($_SERVER['HTTPS'...
$main_category = get_queried_object();
$main_category_id = $main_category->term_id;
$main_category_name = $main_category->name;
$main_category_slug = $main_category->slug;
foreach(get_terms('product_cat',  $main_category_id) as $term)
{
    if($term->slug == "genre")
    {
        foreach(get_terms('product_cat', ['parent' => $term->term_id]) as $_gt)
        {
            $genre_dict[] = $_gt->name;
        }
    } // END OF: if($term->slug == "genre"...
    if($term->slug == "year")
    {
        foreach(get_terms('product_cat', ['parent' => $term->term_id]) as $_gt)
        {
            $year_dict[] = $_gt->name;
        }
    } // END OF: if($term->slug == "year"...
} // END OF: foreach(get_terms('product_cat',  $sub_category_id...

$_ARTIST_OBJ = 
[
    'artist_id' => $main_category->term_id,
    'artist_name' => $main_category->name,
    'artist_slug' => $main_category->slug
];
foreach(get_terms('product_cat', ['parent' => $main_category_id]) as $sub_category)
{
    
    $sub_category_id = $sub_category->term_id;
    $sub_category_name = $sub_category->name;
    $sub_category_slug = $sub_category->slug;

    $_ARTIST_OBJ['artist_albums'][$sub_category->slug] = 
    [
        'album_id' => $sub_category->term_id,
        'album_name' => $sub_category->name,
        'album_slug' => $sub_category->slug,
        'album_year' => "",
        'album_genre' => "",
        'album_artwork' => $GLOBALS['base_href'].'wp-content/uploads/album_images/'.$sub_category->slug.'.jpg',
        'album_tracks' => []
    ];

    $product_loop = new WP_Query
    (
        [
            'post_type' => 'product',
            'product_cat' => $sub_category_name,
            'field' => $sub_category_id
        ]
    );
    if($product_loop->have_posts())
    {
        while($product_loop->have_posts())
        {
            $product_loop->the_post();
            global $product;
            $_ARTIST_OBJ['artist_albums'][$sub_category->slug]['album_tracks'][$product->get_slug()] = 
            [
                'track_id' => $product->get_id(),
                'track_name' => $product->get_name(),
                'track_slug' => $product->get_slug(),
                'track_sku' => $product->get_sku(),
                'track_preview' => $GLOBALS['base_href'].'wp-content/uploads/audio/samples/'.strtolower(str_replace(array(" ", "-"), "", $product->get_name().$product->get_sku())).'-sample.mp3'
            ];
            foreach(get_the_terms($product->get_id(), 'product_cat') as $term)
            {
                if(in_array($term->name, $genre_dict))
                {
                    $_ARTIST_OBJ['artist_albums'][$sub_category->slug]['album_genre'] = $term->name;
                } // END OF: if(in_array($term->name, $genre_dict...
                if(in_array($term->name, $year_dict))
                {
                    $_ARTIST_OBJ['artist_albums'][$sub_category->slug]['album_year'] = $term->name;
                } // END OF: if(in_array($term->name, $year_dict...
                
            }

        } // END OF: while($product_loop->have_posts(...
    }
    else
    {
        echo("<p>There are no products...</p>");
    } // END OF: if($product_loop->have_posts(...
} // END OF: foreach(get_terms('product_cat', ['parent' => $main_category_id...

print_r($_ARTIST_OBJ);

Hopefully this may help another Noob that comes across the same challenge somewhere down the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM