Hide products with empty or zero price

  • 1 year, 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’ );

    wpsolr
    Keymaster
    1 year, 6 months ago #30863

    You could activate the WooCommerce inventory “Hide out of stock items from the catalog” option, and mark those items with no-stock. WPSOLR will de-index them.

    1 year, 6 months ago #30865

    Actually, some products are in stock status with empty price, will this work ?

    wpsolr
    Keymaster
    1 year, 6 months ago #30866

    Can’t you mark those products as out of stock?

    1 year, 6 months ago #30867

    No, 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.

    wpsolr
    Keymaster
    1 year, 6 months ago #30869

    The 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 );
Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.