I have an issue that is doing my head in, I'm trying to sort my posts using pre_get_posts by and ACF field that is a text field.
Here is my code:
function my_pre_get_posts( $query ) {
// do not modify queries in the admin
if( is_admin() ) {
return $query;
}
if( $query->is_main_query() && $query->is_tax('locations')) {
$query->set('meta_key', 'level');
$query->set('orderby', 'meta_value');
$query->set('order', 'DESC');
}
// return
return $query;
}
add_action('pre_get_posts', 'my_pre_get_posts');
In the ACF config, it's set to text and the values of this text can be Bronze, Silver, Gold etc.
UPDATE
I've now changed the level field to a number and switch it round 1 = Bronze, 2 = Silver etc.
Still, I get nothing.
When I run the below nothing gets returned.
Any ideas?
I think you could be inadvertently overwriting the whole query. Try this (untested) snippet:
function my_pre_get_posts( $query ) {
if( ! is_admin() && $query->is_main_query() && $query->is_tax('locations')) {
$query->set('meta_key', 'level');
$query->set('orderby', 'meta_value');
$query->set('order', 'DESC');
}
}
add_action('pre_get_posts', 'my_pre_get_posts');
Note that $query is not returned.
Good luck!
So in the end of switched it from the functions.php file to the taxonomy template.
Here is my finished code:
<?php
if(isset($_GET['type'])) {
if($_GET['type'] == 'villa') {
$filter = array(
'key' => 'type_name',
'value' => 'Villa',
'compare' => '=',
);
} elseif ($_GET['type'] == 'apartment') {
$filter = array(
'key' => 'type_name',
'value' => 'Apartment',
'compare' => '=',
);
} elseif ($_GET['type'] == 'alls') {
$filter = array(
'relation' => 'or',
array(
'key' => 'type_name',
'value' => 'Villa',
'compare' => '=',
),
array(
'key' => 'type_name',
'value' => 'Apartment',
'compare' => '=',
)
);
}
}
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'properties',
'post_per_page' => 12,
'paged' => $paged,
'meta_key' => 'level',
'orderby' => 'meta_value',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'locations',
'field' => 'slug',
'terms' => $term->slug,
),
),
'meta_query' => $filter
);
// the query
$the_query = new WP_Query( $args ); ?>
Fingers crossed it helps someone else.
Related
SOLVED!
I have a custom post with some metabox and taxonomy. I'm trying to filter custom posts by combination of meta value and taxonomy and it's working as expected. When both meta value and taxonomy selected it's returning correct result, only taxonomy selection is also working. But if I select only meta value and try to filter post it's returning nothing. Here I'm sharing a video link of the output: https://youtu.be/XaCeJ_LcPhc. Is is possible to solve the issue without custom query?
$category_array= [];
$metabox_array = [];
foreach($_POST as $key => $value){
if($key == 'ms_product_categories'){
foreach($value as $cat_slug){
array_push( $category_array, $cat_slug);
}
}else{
array_push( $metabox_array, array('key' => $key, 'value' => $value ) );
}
}
if(count($metabox_array) >= 2){
$relation = "'relation'=>'AND'";
}else{
$relation = '';
}
$args = array(
'post_type' => 'ms_product',
'meta_query' => array(
$relation,
$metabox_array
),
'tax_query' => array(
array(
'taxonomy' => 'ms_product_categories',
'field' => 'slug',
'terms' => $category_array
),
)
);
$ms_products = new WP_Query( $args );
Here is the solution, maybe it will be helpful for someone.
$category_array= [];
$metabox_array = [];
foreach($_POST as $key => $value){
if($key == 'ms_product_categories'){
foreach($value as $cat_slug){
array_push( $category_array, $cat_slug);
}
}else{
array_push( $metabox_array, array('key' => $key, 'value' => $value ) );
}
}
if(count($metabox_array) > 1){
$metabox_array['relation'] = 'AND';
}
if(!empty($category_array)){
$tax_query = array(
'taxonomy' => 'ms_product_categories',
'field' => 'slug',
'terms' => $category_array,
'include_children' => true,
);
}else{
$tax_query = '';
}
$args = array(
'post_type' => 'ms_product',
'meta_query' => $metabox_array,
'tax_query' => array(
$tax_query
)
);
I want to get a list of products with sku and post id with this code, everything seems fine and ok with this code :
$statuses = array('publish', 'draft');
// Args on the main query for WC_Product_Query
$args = [
'status' => $statuses,
'orderby' => 'name',
'order' => 'ASC',
'limit' => -1,
];
$vendor_products = wc_get_products($args);
$list_array = array();
foreach ($vendor_products as $key => $product) {
if ($product->get_type() == "variable") {
// Args on product variations query for a variable product using a WP_Query
$args2 = array(
'post_parent' => $product->get_id(),
'post_type' => 'product_variation',
'orderby' => array( 'menu_order' => 'ASC', 'ID' => 'ASC' ),
'fields' => 'ids',
'numberposts' => -1,
);
foreach ( get_posts( $args2 ) as $child_id ) {
// get an instance of the WC_Variation_product Object
$variation = wc_get_product( $child_id );
if ( ! $variation || ! $variation->exists() ) {
continue;
}
$list_array[] = array(
'sku' => $variation->get_sku(),
'postid' => $variation->get_id()
);
}
} else {
$list_array[] = array(
'sku' => $product->get_sku(),
'postid' => $product->get_id()
);
}
}
I have total 1660 (470 published and 1,190 drafted) products but it's just returns 501 products and i don't know why!
this is my products in woocommerce:
this is the final result of query :
this is the result of Janki's code
// Woocommerce get all products
$args = array(
'post_type' => array('product','product_variation'),
'meta_key' => '_sku',
'post_status' => array('publish','draft'),
'meta_query' => array(
array(
'key' => '_sku',
'compare' => 'EXISTS',
),
),
);
$products = new WP_Query($args);
/* using this code you can get all products */
/* this may help you to get details */
I am using the following function/shortcode in order to output an average global rating using ACF :
function get_average_rating($post_id) {
$rating_sum = 0;
$reviews_of_post = get_posts( array(
'post_type' => 'avis',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'produit',
'value' => $post_id,
'compare' => '=',
),
),
) );
if ( empty( $reviews_of_post ) ) {
return 0;
}
foreach ( $reviews_of_post as $review ) {
$rating_sum += get_field( 'note_client', 'post_' . $review->ID);
}
return number_format((float)($rating_sum / count( $reviews_of_post )),1, ',', '');
}
add_shortcode( 'note-clients', 'get_average_rating');
It always return 0 except when I manually input the post ID like :
'meta_query' => array(
array(
'key' => 'produit',
'value' => 1234,
'compare' => '=',
),
),
How can I fix this ?
Thanks a lot !
Declare global $post; before your function.
Wordpress uses $post for many of its functions within the loop.
To avoid any conflicts later you should consider use of wp_reset_query
1 . Change key 'key' => 'produit' to 'key' => 'product',
2 .
foreach ( $reviews_of_post as $review ) {
$rating_sum += get_field( 'note_client', 'post_' . $review->ID);
}
**to**
foreach ( $reviews_of_post as $review ) {
$post_id = 'post_' . $review->ID ;
$rating_sum += get_field( 'note_client', $post_id );
}
Confirm ACF key (note_client) is correct
3 . Change this
add_shortcode( 'note-clients', 'get_average_rating');
to
add_shortcode( 'average_rating', 'get_average_rating');
Please try with your post static id:
$post_id = 9; //add here your static post id
$reviews_of_post = get_posts( array(
'post_type' => 'avis',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'produit',
'value' => $post_id,
'compare' => '=',
),
),
) );
I have a custom post type "member" with custom taxonomy "member_category". In this taxonomy I have a custom field (as metadata) called "display".
Now I want to query members from the DB and only recieve members who have the taxonomy with the metadata "display" with value of "1".
My attempt is:
$args = array(
'post_type' => 'member',
'tax_query' => array(
array(
'taxonomy' => 'member_category',
'value' => '1',
'field' => 'term_meta[display]' (????)
'operator' => 'LIKE'
)
));
$query = new WP_Query($args);
But it's not working.
Any idea? Maybe I should use a SQL query? If so, Which $wpdb query should I write?
Thanks
You should first fetch the terms having your desired meta value like this:
$term_args = array('taxonomy' => 'member_category');
$terms = get_terms( $term_args );
$term_ids = array();
if ( ! empty( $terms ) && ! is_wp_error( $terms ) )
{
foreach( $terms as $term )
{
$val = get_term_meta( $term->term_id, 'display', true);
if( $val == '1' ) {
// push the ID into the array
$term_ids[] = $term->ID;
}
}
}
Then passing combined id's on the tax_query as below :
$args = array('post_type' => 'member');
$tax_query = array();
if(sizeof($term_ids))
{
$tax_query = array(
'relation' => 'AND',
array(
'taxonomy' => 'member_category',
'field' => 'ID',
'terms' => $term_ids,
'operator' => 'IN',
)
);
}
if(sizeof($tax_query))
$args['tax_query'] = $tax_query;
You don't need to use SQL queries. If you are querying metadata, you need to use the meta query.
$args = array(
'post_type' => 'member',
'meta_query' => array(
array(
'key' => 'display',
'value' => '1',
)
));
On your args you have everything under tax query which is why it does not work.
I need to get all product in a category that match an attribute.
Here my code:
$title = isset($instance['title']) ? $instance['title'] : '';
$car_type = isset($instance['cartype']) ? $instance['cartype'] : 'usato';
$car_brand = isset($instance['carbrand']) ? $instance['carbrand'] : '';
$limit = isset($instance['limit']) ? $instance['limit'] : null;
$order = $instance['order'];
$carousel = $instance['carousel'];
$query_args = [
'post_type' => 'product',
'post_status' => 'publish',
'product_cat' => $car_type
];
// Ordino i risultati
if ($order == 'random') {
$query_args['orderby'] = 'random';
} else {
$query_args['orderby'] = 'name';
$query_args['order'] = $order;
}
// Devo limitare il numero di risultati?
if ($limit) {
$query_args['posts_per_page'] = $limit;
}
if ($car_brand != '') {
$query_args['tax_query'] = array(
array(
'key' => 'pa_marca',
'value' => 'nike',
'field' => 'slug',
'compare' => '='
)
);
}
The problem is that I always get 0 result even if there is a product with that category and that attribute.
How should I modify the query?
It looks you use tax_query instead of meta_query. tax_query is for taxonomie filter.
Try this:
$query_args['meta_query'] => array(
array(
'key' => 'pa_marca',
'value' => 'nike',
'compare' => '=',
),
);
WP_Query#Custom_Field_Parameters
Finally I get the solution, this is how you need to query on an attribute:
$query_args['tax_query'] = array(
array(
'key' => 'pa_brand',
'field' => 'slug',
'terms' => 'nike'
)
);
Note that in the key you need to add pa_ to your attribute name and you need to use terms to specify the value of your attribute.