我当前的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以便切换?
最合适的回答,由SO网友:Sally CJ 整理而成
你应该打电话wp_localize_script()
在wp_enqueue_scripts
hook (或更高版本的钩子),您可以在其中获得正确的产品/帖子数据,如ID,以及以下条件标记is_single()
也将按预期工作。
所以你应该把所有的$product
, $product_id
, $dataToBePassed
和wp_localize_script()
内部零件wp_enqueue_scripts
回调,然后您将获得正确的产品/帖子ID等。请参见下面的示例,并注意:
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 );
}