所以这是我的插件代码的一部分。我是一个新手,所以要友善。我读过关于全局变量的书,但我似乎无法让它发挥作用,我读到你无论如何都不应该使用它们。那么,在不必为每个函数重新声明变量的情况下,编写下面代码的最佳方法是什么呢?这是full code 如有必要。
// Display the product badge on the shop page
add_action( \'woocommerce_after_shop_loop_item_title\', \'wc_simple_product_badge_display_shop\', 30 );
function wc_simple_product_badge_display_shop() {
$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
$postdate = get_the_time( \'Y-m-d\' ); // post date
$postdatestamp = strtotime( $postdate ); // post date in unix timestamp
$difference = round ((time() - $postdatestamp) / (24*60*60)); // difference in days between now and product\'s post date
if ( !empty( $title ) && empty( $duration ) || !empty( $title ) && $difference <= $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 \' . $class . \'">\' . $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 ) {
$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 = get_the_time( \'Y-m-d\' ); // post date
$postdatestamp = strtotime( $postdate ); // post date in unix timestamp
$difference = round ((time() - $postdatestamp) / (24*60*60)); // difference in days between now and product\'s post date
if ( !empty( $title ) && empty( $duration ) && $single_opt === \'yes\' || !empty( $title ) && $difference <= $duration && $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( $class ) ? $class : \'\';
echo \'<span class="wc_simple_product_badge \' . $class . \'">\' . $title . \'</span>\';
return $img_html;
}
elseif ( $single_opt === \'no\' ) { // Check to see if the checkbox is unchecked to show on single page view
return $img_html;
}
}