Chetan
Chetan

Reputation: 162

WooCommerce - Hide products which has not image

I want to hide all products in woocommerce which have no image.

Can anyone know the appropriate solution as per my requirement?

Thanks

Upvotes: 1

Views: 2321

Answers (2)

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

You can try this code... There can be ways to do it and this is one.

function woocommerce_product_query( $q ) {
    $q->set( 'meta_key', '_thumbnail_id' );
}
add_action( 'woocommerce_product_query', 'woocommerce_product_query' );

This will just make sure _thumbnail_id has a value.

Make sure your product has this empty.
enter image description here


For more general code, please use this

function pre_get_posts( $q ) {
    if ( !is_admin() && $q->is_main_query() && ( $q->get('post_type') == 'product' ) ) {
       $q->set( 'meta_key', '_thumbnail_id' );
    }
}
add_action( 'pre_get_posts', 'pre_get_posts' );

But you should be careful with this, because it will also apply to all product type query in the frontend. You might get unexpected result, that's why there's a lot in the if statement but might need more.

Upvotes: 2

Gufran Hasan
Gufran Hasan

Reputation: 9373

There are so many hooks and filters available in WooCommerce. You can use them and modify or update functionality.

Action and Filter Hook Reference in WooCommerce

Please use hook woocommerce_product_query to modify your query as :

add_action( 'woocommerce_product_query', 'noimage_pre_get_posts_query' );
function noimage_pre_get_posts_query( $query ) {

    $query->set( 'meta_query', array( array(
       'key' => '_thumbnail_id',
       'value' => '0',
       'compare' => '>'
    )));

}

Put this in functions.php file of the theme in WordPress

Upvotes: 1

Related Questions