Skip to content

Instantly share code, notes, and snippets.

@corsonr
Created August 28, 2013 16:20
Show Gist options
  • Save corsonr/6367944 to your computer and use it in GitHub Desktop.
Save corsonr/6367944 to your computer and use it in GitHub Desktop.
WooCommerce - Get featured products IDs
/**
* Function that returns an array containing the IDs of the featured products.
*
* @since 2.0
* @access public
* @return array
*/
function woo_get_featured_product_ids() {
// Load from cache
$featured_product_ids = get_transient( 'wc_featured_products' );
// Valid cache found
if ( false !== $featured_product_ids )
return $featured_product_ids;
$featured = get_posts( array(
'post_type' => array( 'product', 'product_variation' ),
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
),
array(
'key' => '_featured',
'value' => 'yes'
)
),
'fields' => 'id=>parent'
) );
$product_ids = array_keys( $featured );
$parent_ids = array_values( $featured );
$featured_product_ids = array_unique( array_merge( $product_ids, $parent_ids ) );
set_transient( 'wc_featured_products', $featured_product_ids );
return $featured_product_ids;
}
@pierre-dargham
Copy link

It seems that products without parents have id=>parent equal to 0 : this is why $featured_product_ids contains 0 after the merge, which can cause code errors when using the return value of this function.

A simple return array_diff( $featured_product_ids, array( 0 ) ); solve the issue.

Do you agree ?
Best regards,

Pierre D.

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