虽然Toscho的答案没有错,但使用类可以避免这个问题,OP最初的问题是关于globals的使用,因此这些答案应该直接针对这个问题。
---使用全局变量---
在全局范围内(不在函数或类似函数内)定义的任何变量本质上都是全局变量。要访问函数中的全局with,必须使用global关键字,例如。global $myglobal
下面是经过重构的代码,以演示:
<?php
$product_data = array();
// populating the global on a hook before the other two
add_action(\'woocommerce_before_single_product\',\'populate_product_data\');
function populate_product_data() {
global $product_data;
$postdate = get_the_time( \'Y-m-d\' ); // post date
$postdatestamp = strtotime($postdate);
$product_data = array(
\'title\' => get_post_meta( get_the_ID(), \'_wc_simple_product_badge_title\', true ), // badge title
\'class\' => get_post_meta( get_the_ID(), \'_wc_simple_product_badge_class\', true ), // badge class
\'duration\' => get_post_meta( get_the_ID(), \'_wc_simple_product_badge_duration\', true ), // badge duration
\'single_opt\' => get_post_meta( get_the_ID(), \'_wc_simple_product_badge_single_page_option\', true ), // badge on single page
\'postdate\' => $postdate,
\'postdatestamp\' => $postdatestamp, // post date in unix timestamp
\'difference\' => round ((time() - $postdatestamp) / (24*60*60)), // difference in days between now and
);
}
add_action( \'woocommerce_after_shop_loop_item_title\', \'wc_simple_product_badge_display_shop\', 30 );
function wc_simple_product_badge_display_shop() {
global $product_data;
if ( !empty( $product_data[\'title\'] ) && empty( $product_data[\'duration\'] ) || !empty( $product_data[\'title\'] ) && $product_data[\'difference\'] <= $product_data[\'duration\'] ){ // Check to see if there is a title and the product is still within the duration timeframe if specified
$class = !empty( $class ) ? $class : \'\';
echo \'<span class="wc_simple_product_badge \' . $product_data[\'class\'] . \'">\' . $product_data[\'title\'] . \'</span>\';
}
}
// Display the product badge on the single page
add_filter( \'woocommerce_single_product_image_html\', \'wc_simple_product_badge_display_single\' );
function wc_simple_product_badge_display_single( $img_html ) {
global $product_data;
if ( !empty( $product_data[\'title\'] ) && empty( $product_data[\'duration\'] ) && $product_data[\'single_opt\'] === \'yes\' || !empty( $product_data[\'title\'] ) && $product_data[\'difference\'] <= $product_data[\'duration\'] && $product_data[\'single_opt\'] === \'yes\' ){ // Check to see if there is a title and the product is still within the duration timeframe ()if specified) and the checkbox is checked to show on single page view
$class = !empty( $product_data[\'title\'] ) ? $product_data[\'title\'] : \'\';
echo \'<span class="wc_simple_product_badge \' . $product_data[\'class\'] . \'">\' . $product_data[\'title\'] . \'</span>\';
return $img_html;
}
elseif ( $product_data[\'single_opt\'] === \'no\' ) { // Check to see if the checkbox is unchecked to show on single page view
return $img_html;
}
}