Reputation: 65
I am working in WooCommerce API and I would like to make a new endpoint which lists me specific products. We have made previously new fields with a plugin and I would like to check them. If the property is ticked in the settings, then show it, else do not.
The new property of the products (checkbox in advanced settings):
woocommerce_wp_checkbox(
array(
'id' => '_checkbox_badge_hot',
'desc' => __('set the checkbox', 'woocommerce'),
'label' => __('Hot', 'woocommerce'),
'desc_tip' => 'true',
'value' => get_post_meta( $post->ID, '_checkbox_badge_hot', true )
)
);
The Code which should list me the products (now if I try to request to the endpoint it just keeps loading):
function get_hot_products(){
$args_for_hot_product = array(
'post_type' => 'product',
'posts_per_page' => -1
);
$loop = new WP_Query( $args_for_hot_product );
$hotproducts = [];
while ( $loop->have_posts() ) : $loop->the_post();
wc_get_template_part( 'content', 'product' );
endwhile;
while ( $loop->have_posts() ): $loop->the_post(){
$hot = $loop->get_meta('_checkbox_badge_hot');
if( $hot === "yes" ){
array_push($hotproducts, $hot);
}
}
//wp_reset_postdata();
return $hotproducts;
}
add_action( 'rest_api_init', function () {
register_rest_route( '/wc/v3', '/featuredproducts', array(
'methods' => 'GET',
'callback' => 'get_hot_products',
) );
} );
Thanks for your help guys!
Upvotes: 2
Views: 1359
Reputation: 253949
To get and display all products that have a specific custom field value, using a WP_Query
, you will simply use a eta query as follow:
function display_hot_products(){
$loop = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array( array(
'key' => '_checkbox_badge_hot',
'value' => 'yes',
'compare' => '=',
)),
));
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
the_title(); // Display product title
endwhile;
wp_reset_postdata();
endif;
}
Don't forget that when using a WP_Query
you get WC_Post
objects and not WC_Product
Objects.
Upvotes: 2