gpt4 book ai didi

php - 使用自定义元查询显示带有简码的 WooCommerce 产品

转载 作者:行者123 更新时间:2023-12-05 08:54:50 28 4
gpt4 key购买 nike

我正在创建一个闪购网站,并且我已经在主页和商店页面上根据日期范围显示产品。但我也想根据其他地方的日期范围显示产品,因此使用简码。

这是我的代码:

function testt($meta_query)
{
$today = current_time('Ymd');
$args = apply_filters('woocommerce_shortcode_products_query', array (
'post_type' => 'product',
'numberposts' => -1,
'meta_query' => array(
'relation' => 'AND',
'start_clause' => array(
'key'=>'flash_sale_start',
'value' => $today,
'compare'=> '<=',
'type' => 'DATE'
),
'end_clause' => array(
'key' => 'flash_sale_end',
'value' => $today,
'compare' => '>=',
'type' => 'DATE'
),
)));
return $args;
}
add_shortcode( 'test', 'testt' );

但是它没有显示任何东西,甚至我页面的其余内容都消失了。

我做错了什么?

感谢任何帮助。

最佳答案

这是正常的,它不会返回任何内容,因为您需要首先在 WP_Query 中传递此 $args 并在循环中调用产品模板方式:

if( ! function_exists('product_test') ) {

// Add Shortcode
function product_test( $atts ) {
global $woocommerce_loop;

// Attributes
$atts = shortcode_atts(
array(
'columns' => '4',
'limit' => '20',
'start' => current_time('Ymd'),
'end' => current_time('Ymd'),
),
$atts, 'products_test'
);


$woocommerce_loop['columns'] = $atts['columns'];

// The WP_Query
$products = new WP_Query( array (
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => $atts['limit'],
'meta_query' => array(
'relation' => 'AND',
'start_clause' => array(
'key' =>'flash_sale_start',
'value' => $atts['today'],
'compare' => '<=',
'type' => 'DATE'
),
'end_clause' => array(
'key' => 'flash_sale_end',
'value' => $atts['today'],
'compare' => '>=',
'type' => 'DATE'
),
)
));

ob_start();

if ( $products->have_posts() ) { ?>

<?php woocommerce_product_loop_start(); ?>

<?php while ( $products->have_posts() ) : $products->the_post(); ?>

<?php wc_get_template_part( 'content', 'product' ); ?>

<?php endwhile; // end of the loop. ?>

<?php woocommerce_product_loop_end(); ?>

<?php
} else {
do_action( "woocommerce_shortcode_products_loop_no_results", $atts );
echo "<p>There is no results.</p>";
}

woocommerce_reset_loop();
wp_reset_postdata();

return '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';
}

add_shortcode( 'products_test', 'product_test' );
}

代码进入事件子主题(或事件主题)的 function.php 文件。


用法:

您可以将 4 个可用的可选参数添加到此短代码中:

  • columns(列数)- 默认为 4
  • limit(产品数量 | -1 将显示全部)- 默认为 20
  • start(开始日期 | 格式为“YMD”)- 默认为今天
  • end(结束日期 | 格式为“YMD”)- 默认为今天

您可以在函数中设置更多...您也可以更改默认值。

示例 1(带默认值的简单示例):

[products_test]

示例2(一些自定义值)

[products_test columns='3' limit='15']

已测试并有效

关于php - 使用自定义元查询显示带有简码的 WooCommerce 产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48351613/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com