skip to Main Content

I need to show products on a category page using the custom field.

For example, I have custom filed ‘members_access_role’ (multi check) and try

add_action( 'woocommerce_product_query', 'action_product_query', 10, 2 );
function action_product_query( $q, $query ) {

    $meta_query = $q->get( 'meta_query');

    $q->set( 'meta_query', array( array(
        'key'     => 'members_access_role',
        'value'   => 'wholesale',
        'compare' => 'IN',
    ) ) );

    $q->set( 'meta_query', $meta_query );
}

This doesnt work, i try change compare to ‘LIKE’, ‘=’ but nothing too.

2

Answers


  1. Please replace function like this:

    add_action( 'woocommerce_product_query', 'action_product_query', 10, 2 );
    function action_product_query( $q, $query ) {
    
        $meta_query = $q->get( 'meta_query');
    
        $meta_query[] = array(
            'key'       => 'members_access_role',
            'value'     => 'wholesale',
            'compare'   => 'IN'
        );
    
        $q->set( 'meta_query', $meta_query );
    }
    
    Login or Signup to reply.
  2. You seems to be setting meta_query twice and the 2nd time you are setting it is exactly the same as you received using get method.

    Here is one way to write it

    function action_product_query( $q, $query ) {
    
        $meta_query = $q->get( 'meta_query');   //Get the query
    
        //Update the array.
        $meta_query[] = array(
            'key'     => 'members_access_role',
            'value'   => 'wholesale',
            'compare' => '=',
        );
    
        //Set the updated value below.
        $q->set( 'meta_query', $meta_query );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search