Last active
May 19, 2024 03:18
-
-
Save damiencarbery/03c150b8b0440f55483f95107043f7f2 to your computer and use it in GitHub Desktop.
Change WooCommerce [products] shortcode display order - Change the order of products in [products] shortcode to order in ids parameter if 'orderby' is set to 'ids'. https://www.damiencarbery.com/2024/05/change-woocommerce-products-shortcode-display-order/
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 | |
/* | |
Plugin Name: WooCommerce - Change [products] shortcode display order | |
Plugin URI: https://www.damiencarbery.com/ | |
Description: Change the order of products in [products] shortcode to order in ids parameter if 'orderby' is set to 'ids'. Example: [products ids="1,5,2,4" orderby="ids"] | |
Author: Damien Carbery | |
Author URI: https://www.damiencarbery.com | |
Version: 0.1.20240517 | |
*/ | |
// Change order of [products] shortcode results to that specified in 'ids' parameter. | |
add_filter( 'woocommerce_shortcode_products_query_results', 'dcwd_products_query_results', 10, 2 ); | |
function dcwd_products_query_results( $results, $shortcode_class ) { | |
$orderby = $shortcode_class->get_attributes()[ 'orderby' ]; | |
// Ensure 'orderby' is set to 'ids'. | |
if ( ! empty( $orderby ) && 'ids' == $orderby ) { | |
$ids_str = $shortcode_class->get_attributes()[ 'ids' ]; | |
// Do not change anything if the 'ids' parameter is empty. | |
if ( ! empty( $ids_str ) ) { | |
$ids = array_map( 'trim', explode( ',', $ids_str ) ); | |
// Verify that the IDs are in the query results (in case any were invalid). | |
// This isn't really necessary as WooCommerce will skip over invalid IDs. | |
$valid_ids = array(); | |
foreach ( $ids as $id ) { | |
if ( in_array( $id, $results->ids ) ) { | |
$valid_ids[] = $id; | |
} | |
} | |
// And ensure some IDs were provided. | |
if ( count( $valid_ids ) ) { | |
$results->ids = $valid_ids; | |
} | |
} | |
} | |
return $results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment