Created
July 26, 2020 00:48
-
-
Save chrono-meter/289d75f15313f1b2542a70bc3c35655c to your computer and use it in GitHub Desktop.
WooCommerce: Add stock filter function to builtin shortcodes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Description: WooCommerce: Add stock filter function to builtin shortcodes. | |
* Author: chrono-meter@gmx.net | |
* Version: v20200727 | |
* | |
* @link https://docs.woocommerce.com/document/woocommerce-shortcodes/ | |
* | |
* Example: | |
* [products stock="instock"] | |
* [products stock="instock,onbackorder"] | |
*/ | |
class WC_Builtin_Shortcode_Stock_Filter { | |
public $shortcodes = []; | |
/** | |
* @see \WC_Shortcodes::init() | |
*/ | |
public function __construct() { | |
$this->shortcodes = apply_filters( 'WC_Builtin_Shortcode_Stock_Filter/enabled_shortcodes', [ | |
'products', | |
'product_category', | |
'recent_products', | |
'sale_products', | |
'best_selling_products', | |
'top_rated_products', | |
'product', | |
'sale_products', | |
'featured_products', | |
'product_attribute', | |
] ); | |
foreach ( $this->shortcodes as $shortcode ) { | |
add_filter( "shortcode_atts_{$shortcode}", [ $this, 'shortcode_atts' ], 10, 4 ); | |
} | |
add_filter( 'woocommerce_shortcode_products_query', [ $this, 'woocommerce_shortcode_products_query' ], 10, 3 ); | |
} | |
/** | |
* @param array $out | |
* @param array $pairs | |
* @param array $atts | |
* @param string $shortcode | |
* | |
* @return array | |
* | |
* @see \WC_Shortcode_Products::parse_attributes() | |
*/ | |
function shortcode_atts( $out, $pairs, $atts, $shortcode ) { | |
if ( isset( $atts['stock'] ) ) { | |
$out['_stock_status'] = $atts['stock']; | |
} | |
return $out; | |
} | |
/** | |
* @param array $query_args | |
* @param array $atts | |
* @param string $shortcode | |
* | |
* @return array | |
* | |
* @link https://stackoverflow.com/a/45967535/3622941 | |
*/ | |
function woocommerce_shortcode_products_query( $query_args, $atts, $shortcode ) { | |
if ( in_array( $shortcode, $this->shortcodes ) && ! empty( $atts['_stock_status'] ) ) { | |
if ( ! isset( $query_args['meta_query'] ) ) { | |
$query_args['meta_query'] = []; | |
} | |
$query_args['meta_query'][] = [ | |
'key' => '_stock_status', | |
'compare' => 'IN', | |
'value' => explode( ',', $atts['_stock_status'] ), | |
]; | |
} | |
return $query_args; | |
} | |
} | |
new WC_Builtin_Shortcode_Stock_Filter(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment