Hide products with empty or zero price
- prakashreddy.imduriParticipant2 years, 6 months ago #30858
Hi, Can you help us with hiding the products without price or zero price. Without activating the code this pre_get_posts is working, but all results are showing if plugin is activated.
// Exclude out of stock products
function hide_products_no_price( $query ) {
if ( ! is_admin() && $query->is_main_query() ) :
$query->set( ‘meta_query’, array(
array(
‘key’ => ‘_price’,
‘value’ => ‘0’,
‘compare’ => ‘>’,
‘type’ => ‘NUMERIC’
)
) );
endif;
}
add_action( ‘pre_get_posts’, ‘hide_products_no_price’ );prakashreddy.imduriParticipant2 years, 6 months ago #30865Actually, some products are in stock status with empty price, will this work ?
prakashreddy.imduriParticipant2 years, 6 months ago #30867No, we have many products which makes tough to mark them individually… some code to exclude it would be better. Above code is working but without wpsolr activated.
wpsolrKeymaster2 years, 6 months ago #30869The following code in your functions.php should filter out your products without a price from indexing.
Delete the content of your index to remove current indexed products with no price, then reindex.<?php use wpsolr\core\classes\WPSOLR_Events; /** * Modify the SQL query that retrieves all post types to be indexed, to remove products with some condition on _price */ add_filter( WPSOLR_Events::WPSOLR_FILTER_SQL_QUERY_STATEMENT, function ( $sql_statements, $parameters ) { global $wpdb; $model_type = $parameters['model_type']; if ( 'product' === $model_type->get_type() ) { /* * Use a WHERE sub query to filter out posts with _price not > 0 * This is an exemple: fine tune your query as you like */ $sql_statements['WHERE'] .= " AND A.ID in (SELECT post_id from {$wpdb->prefix}postmeta WHERE meta_key = '_price' AND CAST(meta_value as SIGNED) > 0) "; /* * We could also use a JOIN * $sql_statements['JOIN'] .= '...' ; */ } return $sql_statements; } , 10, 2 );
You must be logged in to reply to this topic.