我在一家woocommerce商店工作,在那里我必须展示产品的位置自定义价值。产品属于任何一个地点。我已经完成了几乎50%的插件,在商店页面上的产品正在得到完美的过滤,但功能产品,销售产品,最近的产品等没有得到过滤,因为他们是从woocommerce产品短码生成。
到现在为止,我在管理产品页面添加了一个自定义文件,并在店铺页面上显示了前端的过滤产品。现在我想从短码中过滤产品。
我在管理站点的产品信息页面中添加了自定义字段,代码如下:
/* adding custom product field: location */
function add_custom_product_text_filed(){
global $woocommerce, $post;
$locatons = array('all' => 'All');
$locations_posts = get_posts(array('post_type' => 'location', 'numberposts' => -1));
foreach ($locations_posts as $loc_post) {
$locatons[$loc_post->ID] = $loc_post->post_title;
}
echo '<div class="options_group">';
woocommerce_wp_select(
array(
'id' => '_location',
'label' => __('Location'),
'desc_tip' => true,
'description' => __('Enter the product location here'),
'options' => $locatons,
)
);
echo '</div>';
}下面是根据位置显示产品的代码
/*Get Location Based Products*/
add_action( 'woocommerce_product_query', 'location_products' );
function location_products($q){
if (isset($_COOKIE['wc_location_product_id']) && !empty($_COOKIE['wc_location_product_id']) && !is_null($_COOKIE['wc_location_product_id']) && $_COOKIE['wc_location_product_id'] != 'all') {
$meta_query = $q->get('meta_query');
$meta_query[] = array(
'key' => '_location',
'value' => $_COOKIE['wc_location_product_id'],
'compare' => '=',
);
$q->set('meta_query', $meta_query);
}
}现在我想改变woocommerce产品短码的工作方式(销售产品,特色产品,最新产品等)基于位置自定义字段,因为页面构造器使用短码来显示产品,但我不知道如何改变短码功能的方式。有没有什么钩子或过滤器来完成这项任务,或者有什么例子可以告诉我们如何完成这项任务。非常感谢您的帮助。谢谢。
发布于 2018-12-21 03:11:38
使用woocommerce_shortcode_products_query专用过滤器钩子的以下代码允许更改Woocommerce短码上的产品查询:
add_filter( 'woocommerce_shortcode_products_query', 'shortcode_products_query_on_location', 10, 3 );
function shortcode_products_query_on_location( $query_args, $atts, $loop_name ){
if (isset($_COOKIE['wc_location_product_id']) && !empty($_COOKIE['wc_location_product_id']) && !is_null($_COOKIE['wc_location_product_id']) && $_COOKIE['wc_location_product_id'] != 'all') {
$query_args['meta_query'] = array( array(
'key' => '_location',
'value' => $_COOKIE['wc_location_product_id'],
'compare' => '=',
) );
}
return $query_args;
}代码放在活动子主题(或活动主题)的function.php文件中。应该能行得通。
https://stackoverflow.com/questions/53874323
复制相似问题