LOCALIZE_SCRIPT但数据根据产品ID更改

时间:2021-07-18 作者:sico87

我当前的functions.php 文件

$dataToBePassed = array();
add_action( \'wp_enqueue_scripts\', function() {
        $handle  = \'three-d-scripts\';
        $src     = get_stylesheet_directory_uri() . \'/src/scripts/three-d-scripts.js\';
        $deps    = [];
        $version = \'1.0.0\';
        wp_enqueue_script( $handle, $src, $deps, $version, true );
} );
wp_localize_script( \'three-d-scripts\', \'php_vars\', $dataToBePassed );
我想做的是更改dataToBePassed 根据当前查看产品的产品ID,这是否可能?

我试过了,

global $product; $product->get_id();

但它返回NULL,

global $post; $post->ID;

我希望实现的是,

global $product;
$product_id = $product->get_id();
$dataToBePassed = array();
add_action( \'wp_enqueue_scripts\', function() {
        $handle  = \'three-d-scripts\';
        $src     = get_stylesheet_directory_uri() . \'/src/scripts/three-d-scripts.js\';
        $deps    = [];
        $version = \'1.0.0\';
        wp_enqueue_script( $handle, $src, $deps, $version, true );
} );
switch($product_id) {
    case 1:
        //do something
    break;
    case 2:
        //do something
    break;
    default:
       //do something
    break;

}
wp_localize_script( \'three-d-scripts\', \'php_vars\', $dataToBePassed );
有没有办法获得woocommerce产品ID以便切换?

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

你应该打电话wp_localize_script()wp_enqueue_scripts hook (或更高版本的钩子),您可以在其中获得正确的产品/帖子数据,如ID,以及以下条件标记is_single() 也将按预期工作。

所以你应该把所有的$product, $product_id, $dataToBePassedwp_localize_script() 内部零件wp_enqueue_scripts 回调,然后您将获得正确的产品/帖子ID等。请参见下面的示例,并注意:

  • is_product()wc_get_product() WooCommerce是函数吗?我之所以使用前者,是因为我认为您的脚本应该只加载在单个产品页面上?(例如example.com/product/product-foo/)

    还有,就像一个人应该做的那样$post = get_post(), 你也应该这样做$product = wc_get_product() 正确获取当前产品/发布对象/数据。

add_action( \'wp_enqueue_scripts\', \'my_theme_enqueue_three_d_scripts\' );
function my_theme_enqueue_three_d_scripts() {
    if ( ! is_product() ) {
        return;
    }

    $handle  = \'three-d-scripts\';
    $src     = get_stylesheet_directory_uri() . \'/src/scripts/three-d-scripts.js\';
    $deps    = array();
    $version = \'1.0.0\';
    wp_enqueue_script( $handle, $src, $deps, $version, true );

    $product        = wc_get_product();
    $product_id     = $product ? $product->get_id() : 0;
    $dataToBePassed = array();

    switch ( $product_id ) {
        case 1:
            $dataToBePassed = array( \'product_id\' => 1 );
            break;

        case 2:
            $dataToBePassed = array( \'product_id\' => 2 );
            break;

        default:
            $dataToBePassed = array( \'product_id\' => 0 );
            break;
    }

    // PS: Instead of php_vars, use a unique name like my_three_d_vars..
    wp_localize_script( $handle, \'php_vars\', $dataToBePassed );
}

相关推荐

Problem in functions.php file

我正在尝试使用functions.php. 以下是我迄今为止所做的工作: <?php function blogroom() { wp_enqueue_style(\'bootstrap\', get_stylesheet_directory_uri() . \'/assets/lib/bootstrap/dist/css/bootstrap.min.css\'); wp_enqueue_style(\'loade