在我之前的问题之后,我有一个问题:Problem in displaying the WordPress shortcode function randomly和Calling multiple variables integrated with HTML in PHP arrays
正如我在上一个问题中所问的,我想防止重复的短码内容出现在我的内容页面上(例如,我可能在一篇文章中使用这个短码5次,我不想在那5次中有重复的内容.即使我总共有4个产品,并且使用了这个短码5次,少了一个产品会显示替代文本而不是显示重复的产品),并且我上一个问题的代码是正确的,但是现在我想将产品的值整合到我之前的代码中,而我在下面写的代码是不正确的,因为有时它会显示重复的产品(我在WordPress帖子中使用这些短码)
我的代码是:
function get_product_id() {
$args = array(
'limit' => -1,
'status' => 'publish',
'return' => 'ids',
);
$all_products = wc_get_products( $args );
$key = array_rand($all_products);
$products_id = $all_products[$key];
return $products_id;
}
function my_shortcode() {
$products_id = get_product_id();
$product = wc_get_product( $products_id );
$product_price = $product->get_price();
$product_sale_price = $product->get_sale_price();
$product_regular_price = $product->get_regular_price();
if (isset($product_price) && $product_price > 0) {
$product_price = number_format($product_price);
}
if (isset($product_sale_price) && $product_sale_price > 0) {
$product_sale_price = number_format($product_sale_price);
}
if (isset($product_regular_price) && $product_regular_price > 0) {
$product_regular_price = number_format($product_regular_price);
}
$product_price_currency_symbol = get_woocommerce_currency_symbol();
$image_id = $product->get_image_id();
$product_image = wp_get_attachment_image_url( $image_id, 'full' );
$product_title = $product->get_title();
$product_link = $product->get_permalink();
$discount = '';
if ( $product->is_on_sale() ) {
$max_percentage = 0;
$percentage = 0;
$price = $product->get_regular_price();
$sale = $product->get_sale_price();
if ( $price != 0 && ! empty( $sale ) ) {
$percentage = ( $price - $sale ) / $price * 100;
}
if ( $percentage > $max_percentage ) {
$max_percentage = $percentage;
}
if ($max_percentage <> 0) {
$discount = '<div class="saved-sale">-' . round($max_percentage) . '% Off</div>';
}
} else {
$product_regular_price = '';
}
$values = [
'1' => '
<a href="' . $product_link . '">
<img src="' . $product_image . '">
<span> '. $discount .' </span>
<span> ' . $product_title . ' </span>
</a>
',
];
if ( ! isset( $GLOBALS['my_shortcode_used'] ) ) {
$GLOBALS['my_shortcode_used'] = [];
}
$post_id = get_the_ID();
if ( ! isset( $GLOBALS['my_shortcode_used'][ $post_id ] ) || ! is_array( $GLOBALS['my_shortcode_used'][ $post_id ] ) ) {
$GLOBALS['my_shortcode_used'][ $post_id ] = [];
}
$unused_values = array_diff( $values, $GLOBALS['my_shortcode_used'][ $post_id ] );
if ( empty( $unused_values ) ) {
$GLOBALS['my_shortcode_used'][ $post_id ] = [];
$unused_values = $values;
}
$key = array_rand( $unused_values );
$GLOBALS['my_shortcode_used'][ $post_id ][] = $unused_values[ $key ];
return $unused_values[ $key ];
}
add_shortcode('jock', 'my_shortcode');
这个代码是否正确和标准?如果没有,请告诉我问题出在哪里,我应该做哪些更改.
有没有一种解决方案不需要我重复几次$values
内的数组?