Skip to content

Instantly share code, notes, and snippets.

@kharissulistiyo
Last active May 2, 2022 16:25
Show Gist options
  • Save kharissulistiyo/547df4c2216d0a492d33 to your computer and use it in GitHub Desktop.
Save kharissulistiyo/547df4c2216d0a492d33 to your computer and use it in GitHub Desktop.
Extending WooCommerce Product Shortcode
<?php
/**
* Extending query parameter of product shortcode
*/
add_filter('woocommerce_shortcode_products_query', 'my_wc_shortcode_product_query_args', 10, 2);
function my_wc_shortcode_product_query_args($args, $atts){
if ( isset( $atts['item'] ) ) {
$args['posts_per_page'] = $atts['item'];
}
if ( isset( $atts['author'] ) ) {
$args['author'] = $atts['author'];
}
return $args;
}
@devidw
Copy link

devidw commented May 2, 2022

Awesome – thanks ✨


For those interested in actually receiving the data from user input: We have to assign them using the shortcode_atts_products hook via add_filter and pass the custom $atts values to the $out values first: https://developer.wordpress.org/reference/hooks/shortcode_atts_shortcode/

Example from OOP context:

public function addAtts(
    array $out,
    array $pairs,
    array $atts,
    string $shortcode
): array {
    $out['item'] = isset($atts['item']) ? $atts['item'] : '';
    $out['author'] = isset($atts['author']) ? $atts['author'] : '';
    return $out;
}

Here item and author could be anything custom attribute from the [products] shortcode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment