我试图将脚本添加到特定的产品类别页面,但代码没有将其添加到类别中。
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\');
但上述代码不起作用。
Product Category URL:
wp-admin/term.php?taxonomy=product_cat&tag_ID=9&post_type=product
最合适的回答,由SO网友:Sally CJ 整理而成
in_category() 应该在循环内使用(除非将post ID作为第二个参数传递,如in_category( 1, 1 )) 并且仅适用于默认/内置category 分类学
对于自定义分类法,如product_cat 在您的情况下,您应该使用has_term(); 但是,如果要检查当前请求/页面是否是分类法归档页面,则应使用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
}
}
或者在WooCommerce(你正在使用WooCommerce,对吧?),您可以使用
is_product_category(), 但你需要知道slug这个词:
function wpb_hook_faqtocategory_javascript() {
if ( is_product_category( \'term-slug\' ) ) {
// ... your code here ...
}
}