I am trying to add the script to the particular Product Category page, but the code is not adding it to the category.
Page (working):
function wpb_hook_faq_javascript() {
if (is_single ('8') || is_page ('8')) {
?>
<script type="application/ld+json">
</script>
<?php }
}
add_action('wp_footer', 'wpb_hook_faq_javascript');
Product Category (not working):
function wpb_hook_faqtocategory_javascript() {
if ( in_category( 'category-name' )) {
?>
<script type="application/ld+json">
</script>
<?php }
}
add_action('wp_footer', 'wpb_hook_faqtocategory_javascript');
But the above code is not working.
Product Category URL:
wp-admin/term.php?taxonomy=product_cat&tag_ID=9&post_type=product
I am trying to add the script to the particular Product Category page, but the code is not adding it to the category.
Page (working):
function wpb_hook_faq_javascript() {
if (is_single ('8') || is_page ('8')) {
?>
<script type="application/ld+json">
</script>
<?php }
}
add_action('wp_footer', 'wpb_hook_faq_javascript');
Product Category (not working):
function wpb_hook_faqtocategory_javascript() {
if ( in_category( 'category-name' )) {
?>
<script type="application/ld+json">
</script>
<?php }
}
add_action('wp_footer', 'wpb_hook_faqtocategory_javascript');
But the above code is not working.
Product Category URL:
wp-admin/term.php?taxonomy=product_cat&tag_ID=9&post_type=product
Share
Improve this question
edited Mar 24, 2020 at 0:06
WordPress Speed
2,2833 gold badges19 silver badges34 bronze badges
asked Mar 22, 2020 at 8:35
Rahul KumarRahul Kumar
2074 silver badges20 bronze badges
1 Answer
Reset to default 3in_category()
should be used inside The Loop (unless if you pass a post ID as the second parameter like in_category( 1, 1 )
) and only for the default/built-in category
taxonomy.
For custom taxonomies like the product_cat
in your case, you should use has_term()
; however, if you're checking if the current request/page is a taxonomy archive page, you should instead use is_tax()
:
function wpb_hook_faqtocategory_javascript() {
if ( is_tax( 'product_cat', 9 ) ) { // 9 is the term ID, but you can use the slug/name
?>
<script type="application/ld+json">
</script>
<?php
}
}
Or in WooCommerce (you're using WooCommerce, right?), you can use is_product_category()
, but you'll need to know the term slug:
function wpb_hook_faqtocategory_javascript() {
if ( is_product_category( 'term-slug' ) ) {
// ... your code here ...
}
}