Created
March 29, 2023 16:43
-
-
Save bluantinoo/e62b1b8e52804d92b1cded3219b4b169 to your computer and use it in GitHub Desktop.
Wordpress pre_get_post valid both for standard and ajax requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Pre get posts valid both for standard and ajax requests | |
* on ajax request we can specify the provider (in this case we're using elementor pro archive) and post type | |
*/ | |
add_action( 'pre_get_posts', 'my_products_pre_get_posts'); | |
function my_products_pre_get_posts( $wp_query ){ | |
if ( wp_doing_ajax() ) { | |
// here is specified the epro-archive/default provider as we are using the filters for elementor built archive | |
$products_query = boolval( isset( $_REQUEST['provider'] ) && $_REQUEST['provider'] === 'epro-archive/default' && 'product' == $wp_query->get( 'post_type' ) ); | |
$ajax = true; | |
} else { | |
$ajax = false; | |
$products_query = boolval( ! is_admin() && ( is_post_type_archive( 'product' ) || is_tax(array('product_cat')) || iic_is_wc_attribute() ) && $wp_query->is_main_query() ); | |
} | |
$tax_query = (array) $wp_query->get( 'tax_query' ); | |
// don't get posts from specific taxonomy term | |
$tax_query[] = array( | |
'taxonomy' => 'custom_cat', | |
'field' => 'slug', | |
'terms' => array( 'custom_cat-slug' ), // Don't display products in the proficiency-test category on the shop page. | |
'operator' => 'NOT IN' | |
); | |
// don't get Woocommerce hidden products | |
$tax_query[] = array( | |
'taxonomy' => 'product_visibility', | |
'field' => 'slug', | |
'terms' => array( 'exclude-from-search', 'exclude-from-catalog' ), // Don't display products that are hidden from search and catalog (woocommerce setup) | |
'operator' => 'NOT IN' | |
); | |
if ( $products_query ){ | |
// custom order | |
$wp_query->set('orderby', 'menu_order'); | |
$wp_query->set('order', 'ASC'); | |
$wp_query->set( 'tax_query', $tax_query ); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment