【问题标题】:How to include WooCommerce conditional tags in custom plugin如何在自定义插件中包含 WooCommerce 条件标签
【发布时间】:2021-06-21 17:15:09
【问题描述】:

我需要使用 WooCommerce 插件中的条件标签 is_product(),因此我的自定义插件仅在用户位于前端的产品页面时才会加载到脚本中。

此外,如果网站上未安装 WooCommerce,我不希望插件中断。

我当前的代码:

if ( !is_admin() && is_product() ) {
    function add_script() {
        wp_enqueue_script( 'main', plugin_dir_url( __FILE__ ) . '/js/main.js' );
    }
}
add_action( 'wp_enqueue_scripts', 'add_script' );

这暂时不起作用,因为它找不到条件标签is_product()

有什么建议吗?

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    “如果网站上没有安装 Woocommerce,我不希望插件中断。” 您的主插件文件应该以:

    // Exit if accessed directly
    if ( ! defined( 'ABSPATH' ) ) exit;
    
    // Check if WooCommerce is active
    if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) exit; // Exit if WC not active
    

    如果用户在产品页面,则加载脚本,使用:

    function add_script() {
        // is_admin() - Determines whether the current request is for an administrative interface page.
        // is_product() - Returns true on a single product page.
        if ( !is_admin() && is_product() ) {
            wp_enqueue_script( 'main', plugin_dir_url( __FILE__ ) . '/js/main.js' );
        }
    }
    add_action( 'wp_enqueue_scripts', 'add_script' );
    

    【讨论】:

      猜你喜欢
      • 2012-06-06
      • 2012-01-14
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 2011-01-23
      • 2012-12-22
      • 2017-12-22
      • 2012-01-31
      相关资源
      最近更新 更多