0

So I have a code which filters my post depending on my custom field. This code filters my posts depending on user role, and which custom field is selected. I successfully managed to filter my post with this code. But it destroyed my sorting when sorting by price or other sorting parameters.

function hideProductDependingOnVisibility( $q ) {

// Get all product IDs
$products_IDs = new WP_Query( array(
    'post_type' => 'product',
    'posts_per_page' => -1,
));

$array_of_product_id = array();
$retailerIds = array();
$wholesalerIds = array();

$user = wp_get_current_user();

while ($products_IDs->have_posts() ) : $products_IDs->the_post();
    $postId = get_the_id();
    $productVisibilities = get_field('show_product_for_accounts', $postId);

    array_push($array_of_product_id, $postId);

    foreach ($productVisibilities as $productVisibility) {
        if ($productVisibility == "retailer") {
            array_push($retailerIds, $postId);
        }

        if ($productVisibility == "wholesale") {
            array_push($wholesalerIds, $postId);
        }
    }

endwhile;


$nonWholeSaleIds = array_diff($array_of_product_id,$wholesalerIds);
$nonRetailerIds = array_diff($array_of_product_id,$retailerIds);

if ( $user->roles[0] == "wholesaler" ) {
    $q->set( 'post__in', $nonWholeSaleIds );
} else {
    $q->set( 'post__in', $nonRetailerIds );
}

}
add_action( 'woocommerce_product_query', 'hideProductDependingOnVisibility' );

I also tried to remove all code and statically changed the queried the products with having only this code instead:

$q->set( 'post__in', 'some product ids');

Yet it still does not sort products properly.

Is there any issue in using post__in and order for WP_Query? or I got something wrong here?

  • Hello and welcome to WordPress SE. Take a moment to look through the help pages as this site differs from a forum in some very important ways. For example, questions about third-party plugins (such as woocommerce) are currently considered off-topic. – Matthew Brown aka Lord Matt Sep 1 '19 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.