我使用Woocommerce和高級自定義字段來管理產品。我想在子分類頁面上顯示父分類圖像。使用Woocommerce和ACF獲取父分類定製字段
其實,我用這個片段來獲得分類父頁上的圖像(它的工作原理):
<?php
$queried_object = get_queried_object();
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;
?>
<img src="<?php the_field('grosse_image_carre', $queried_object); ?>" />
爲了便於參考,這裏是每一個變量的var_dump:
queried_object
object(stdClass)#5089 (10) { ["term_id"]=> int(341) ["name"]=> string(12) "France Laure" ["slug"]=> string(12) "france-laure" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(341) ["taxonomy"]=> string(11) "product_cat" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(185) ["filter"]=> string(3) "raw" }
分類
string(11) "product_cat"
term_id
int(341)
我的問題:如何獲取父類的圖像時,我是一個子類別頁面上?
編號:Get values from a taxonomy term
編輯
我想提出的解決方案,我用這個完整的代碼:
<?php
$queried_object = get_queried_object();
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;
if($queried_object->parent) {
$parent = $queried_object->parent;
echo 'parent: '.$parent.'<br />';
while($parent) {
$cat = get_category($parent);
echo 'Cat: '.$cat.'<br />';
$parent = $cat->category_parent; // Line 30
echo 'parent: '.$parent.'<br />';
$term_id = $cat->cat_ID; // Line 32
echo 'term_id: '.$term_id.'<br />';
}
}
?>
但我得到
parent: 359
Cat:
Notice: Trying to get property of non-object in ...woocommerce\subcat-archive-product.php on line 30
parent:
Notice: Trying to get property of non-object in E...woocommerce\subcat-archive-product.php on line 32
term_id:
編輯2
我跟着喬希編輯2它終於工作!我用
<img src="<?php the_field('grosse_image_carre', 'product_cat_'.$term_id); ?>" />
如果我想返回,直到它獲得頂級父ID,我該怎麼辦? 會有幫助嗎? http://alex.leonard.ie/2011/04/20/wordpress-get-id-of-top-level-parent-category/ –
查看我更新的問題獲取我收到的錯誤。 –
對不起。忘記了我們正在使用定製分類法。我再次更新了我在WooCommerce安裝中測試過的新代碼,它正在工作。此外,如果您想回顯變量,請確保在** while循環之外(最好在它之後)執行此操作。您也必須** print_r ** ** $ cat **變量,因爲這將是一個對象而不是一個字符串。 –