LoginSignup
7
6

More than 5 years have passed since last update.

WooCommerceの商品カテゴリ・タグのデータだけ取得する

Posted at

商品カテゴリ・タグのHTMLは以下の関数で取得できる。

$Product = new WC_Product( $product_id );
$Product->get_categories();
$Product->get_tags();

この2つの関数は「get_the_term_list」のラッパー関数なので、データだけ取りたい場合はそれぞれの関数がget_the_term_listに投げている値を見ながらget_the_terms関数に置き換えれば良い。

$data['tag'] = get_the_terms( $product_id, 'product_tag');
$data['cat'] = get_the_terms( $product_id, 'product_cat');

get_the_termsはオブジェクトの配列を返してくるので、特定の値だけ取りたい場合はこんな感じにすればとりあえずOK。


$data['tag'] = get_term_name_list( get_the_terms( $product_id, 'product_tag') );
$data['cat'] = get_term_name_list( get_the_terms( $product_id, 'product_cat') );

function get_term_name_list( $terms ) {
    foreach ( $terms as $key => $value ) {
        $term_name_list[] = $value->name;
    }
    return $term_name_list;
}
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6