有三种方法可以做到这一点:
1) 创建“免费”类别,并将其分配给所有价格为“0”的产品。然后将“产品类别”小部件放在侧栏中,这样用户就可以单击“免费”类别,它将显示所有类别中价格为零的所有产品。
2) 此选项涉及一些代码,但不只是提供免费产品。相反,它列出了所有类别的免费产品Sale price 设置为零,然后按其Sale price.
在第二个选项中,您不需要去编辑所有产品以分配“免费”类别。只需在主题函数中粘贴以下代码即可。php文件。
一旦此代码就位,它将显示Sort by "For Free" 商店页面上排序下拉列表中的选项。选择它将得到如上所述的结果。
<?php
//Adds WooCommerce catalog sorting options using postmeta, such as custom fields
function pn_add_postmeta_ordering_args( $sort_args ) {
$orderby_value = isset( $_GET[\'orderby\'] ) ? wc_clean( $_GET[\'orderby\'] ) : apply_filters( \'woocommerce_default_catalog_orderby\', get_option( \'woocommerce_default_catalog_orderby\' ) );
// $orderby_value = wc_clean( $_GET[\'orderby\'] ) ;
switch( $orderby_value ) {
// Name your sortby key whatever you\'d like; must correspond to the $sortby in the next function
case \'free\':
$sort_args[\'orderby\'] = \'_price\';
$sort_args[\'meta_key\'] = \'_price\';
$sort_args[\'meta_value\'] = \'0\';
break;
}
return $sort_args;
}
add_filter( \'woocommerce_get_catalog_ordering_args\', \'pn_add_postmeta_ordering_args\' );
// Add the new sorting arguments to the sortby options on the frontend
function pn_add_new_postmeta_orderby( $sortby ) {
// Adjust the text as desired
$sortby[\'free\'] = __( \'Sort by "For Free"\', \'woocommerce\' );
return $sortby;
}
add_filter( \'woocommerce_default_catalog_orderby_options\', \'pn_add_new_postmeta_orderby\' );
add_filter( \'woocommerce_catalog_orderby\', \'pn_add_new_postmeta_orderby\' );
?>
3)您可以创建短代码
[free_products columns="4"]
它将只列出免费产品,并在供应商文档中提到,他们可以在页面中使用该短代码列出免费产品。下面是短代码的代码。您可以将其放置在主题的函数中。php文件。
<?php
add_shortcode(\'free_products\', \'pn_free_products\');
function pn_free_products( $atts ) {
$atts = shortcode_atts( array(
\'columns\' => \'4\',
\'orderby\' => \'title\',
\'order\' => \'asc\',
), $atts );
$query_args = array(
\'post_type\' => \'product\',
\'post_status\' => \'publish\',
\'ignore_sticky_posts\' => 1,
\'orderby\' => $atts[\'orderby\'],
\'order\' => $atts[\'order\'],
\'posts_per_page\' => 12,
\'meta_query\' => array(
array(
\'key\' => \'_price\',
\'value\' => 0,
\'compare\' => \'=\',
\'type\' => \'NUMERIC\'
)
)
);
$products = new WP_Query($query_args);
$columns = $atts[\'columns\'] ;
$woocommerce_loop[\'columns\'] = $columns;
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 {
echo __( \'No products found\' );
}
woocommerce_reset_loop();
wp_reset_postdata();
return \'<div class="woocommerce columns-\' . $columns . \'">\' . ob_get_clean() . \'</div>\';
}
?>