{"id":13806712,"date":"2020-12-18T08:19:09","date_gmt":"2020-12-18T08:19:09","guid":{"rendered":"https:\/\/wordpress.org\/support\/topic\/custom-variable-for-parent-product-category\/"},"modified":"2020-12-18T08:19:09","modified_gmt":"2020-12-18T08:19:09","slug":"custom-variable-for-parent-product-category","status":"publish","type":"topic","link":"https:\/\/wordpress.org\/support\/topic\/custom-variable-for-parent-product-category\/","title":{"rendered":"Custom Variable for Parent Product Category"},"content":{"rendered":"<p>I am trying to create a custom variable that displays the parent category of a custom taxonomy, in this case, WooCommerce product_cat. I got excited before I started seeing some weird behavior. <\/p>\n<p>It&#8217;s kinda weird though, hoping someone can clarify because on some categories it doesn&#8217;t work. On the handful where it doesn&#8217;t display the parent it displays either the same category you are on (already in the title) or in one case it just picked a random child category to display. <\/p>\n<p>Using %%parent_category%% to display using the code below. <\/p>\n<p>Does anyone have any idea what&#8217;s going on? <\/p>\n<pre><code>function get_parent_category() {\n    global $post;\n    \/\/ Get the terms for the current post in your tax\n    $myterms = get_the_terms( $post-&gt;ID, &#039;product_cat&#039; );\n    \/\/ Check if parent exists\n    if ($myterms[0]-&gt;parent !== 0){\n        \/\/ Get the term object\n        $parent = get_term_by(&#039;id&#039;, $myterms[0]-&gt;parent, &#039;product_cat&#039;);\n        return $parent-&gt;name;\n    }\n}\n\nfunction register_custom_yoast_variables() {\n   wpseo_register_var_replacement( &#039;parent_category&#039;, &#039;get_parent_category&#039;, &#039;advanced&#039;, &#039;some help text&#039; );\n}\nadd_action(&#039;wpseo_register_extra_replacements&#039;, &#039;register_custom_yoast_variables&#039;);<\/code><\/pre>\n","protected":false},"template":"","class_list":["post-13806712","topic","type-topic","status-publish","hentry","topic-tag-yoast"],"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/wordpress.org\/support\/wp-json\/wp\/v2\/topic\/13806712","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/wordpress.org\/support\/wp-json\/wp\/v2\/topic"}],"about":[{"href":"https:\/\/wordpress.org\/support\/wp-json\/wp\/v2\/types\/topic"}],"version-history":[{"count":0,"href":"https:\/\/wordpress.org\/support\/wp-json\/wp\/v2\/topic\/13806712\/revisions"}],"wp:attachment":[{"href":"https:\/\/wordpress.org\/support\/wp-json\/wp\/v2\/media?parent=13806712"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}