简体   繁体   English

Woocommerce | 如果page_id = .. {}

[英]Woocommerce | If page_id= .. { }

I am trying to apply specific functions to a certain page ID in Woocommerce. 我正在尝试将特定功能应用于Woocommerce中的特定页面ID。 However, it does not seem to apply. 但是,它似乎并不适用。 I have looked at both Wordpress and Woommerce conditional tags ( https://docs.woocommerce.com/document/conditional-tags/ ). 我已经研究了Wordpress和Woommerce条件标签( https://docs.woocommerce.com/document/conditional-tags/ )。

The simple code I am testing is shown below, but even that is not working. 我正在测试的简单代码如下所示,但即使这样也不起作用。

if ( is_product()) {
    echo ' HALLO sdfdsfsdfsdfsdf ';
}

I have also tried with page_id and post_id but cannot get this to work. 我也尝试过使用page_id和post_id,但是无法使它正常工作。 I have added this code to my functions.php in my child theme. 我已将此代码添加到我的子主题中的functions.php中。

Does anybody know to to write a specific function only for a specific product page (I know the value). 有谁知道只为特定的产品页面编写特定的功能(我知道值)。

Method - 1 方法-1

is_page() relies on a complete global $wp_query object. is_page()依赖于完整的全局$ wp_query对象。 If you call it before the action template_redirect has been fired, it might be impossible to get that data. 如果您在触发操作template_redirect之前调用它,则可能无法获取该数据。

add_filter( 'template_include', function( $template ) {
    if ( is_product() )
        echo 'HELLO';

    return $template;
});

Method - 2 方法-2

The WordPress/ WooCommerce conditional tags won't work until after the wp action is fired, making it the earliest point at which you can use the tags. WordPress / WooCommerce 条件标签要等到wp操作被触发后才起作用,这使其成为最早可以使用标签的地方。 You can view the entire list, and the order of the core WordPress actions at the Action Reference page. 您可以在“操作参考”页面上查看整个列表以及WordPress核心操作的顺序。

add_action( 'wp', 'init' );
function init() {    
  if ( is_shop() ) {    
    echo 'HELLO, this works!';
  }    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM