Last active
November 16, 2020 04:27
-
-
Save DeveloperWil/2d1de8a3f1cf5d58db33606431e1a1bd to your computer and use it in GitHub Desktop.
WooCommerce: Return an array of featured product IDs
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
/** | |
* Return a list (array) of WooCommerce featured product IDs | |
* | |
* @author Wil Brown zeropointdevelopment.com | |
* @return array|mixed | |
*/ | |
function zpd_wc_get_featured_product_ids() { | |
// Load from cache | |
$featured_product_ids = get_transient( 'zpd_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' | |
) ); | |
// Make sure we get rid of any duplicates | |
$product_ids = array_keys( $featured ); | |
$parent_ids = array_values( $featured ); | |
$featured_product_ids = array_unique( array_merge( $product_ids, $parent_ids ) ); | |
set_transient( 'zpd_wc_featured_products', $featured_product_ids ); | |
return $featured_product_ids; | |
} | |
/** | |
* Example Usage | |
* | |
* Use with the WC_Product_Factory object to get a WC_Product object for each ID. | |
* | |
* WC_Product documentation at https://woocommerce.github.io/code-reference/classes/WC-Product.html | |
* | |
*/ | |
$wc_pf = new WC_Product_Factory(); | |
$featured_products_ids = zpd_wc_get_featured_product_ids(); | |
if( $featured_products_ids ){ | |
foreach ( $featured_products_ids as $id ) { | |
$wc_product = $wc_pf->get_product( id) ; | |
// example, get the price | |
$fp_price = $wc_product->get_price(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment