Wordpress: cutom query by custom metadata (meta field) of taxonomy term - wordpress

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.

Related

meta_query is not working with tax_query as expected in WP_query

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
)
);

custom wp_query where meta_key is variable or not needed

To make a custom post type filterable and sortable, i created a custom query that works based on variables in url, accessed by $_GET.
One specific situation breaks it. This is an (un)specified metakey. In the case of sort, the metakey is needed when sorting on a custom field. In the other cases, the metakey can be ignored. However, when i set the variable on empty, the query doesnt produce any posts. How to deal with an empty meta_key?
So far i tried to set the variable as empty ($variable ='');
I set the variable as null; I have used unset.
if (isset($_GET["key"]) || isset($_GET["orderby"])){
if (isset($_GET["key"])) {$key = $_GET["key"];}
else {$key = '';}
if (isset($_GET["value"])) {$value = $_GET["value"]; echo $value;}
else {$value = '';}
if (isset($_GET["orderby"])) {$orderby = $_GET["orderby"];}
if ($orderby='meta_value'){$meta_key='averagerating';}
else {$orderby='';$meta_key='';}
if (isset($_GET["order"])) {$order = $_GET["order"];}
else {$order='';}
$cat = get_queried_object();
if (!empty($cat) && !is_post_type_archive('bedrijf')){
$category = $cat->name;
}
if (is_post_type_archive('bedrijf')){
$category = '';
$terms = get_terms( 'bedrijfs-category' );
// convert array of term objects to array of term IDs
$category = wp_list_pluck( $terms, 'name' );
}
global $post;
$the_query ='';
$args = array(
'post_type' => 'bedrijf',
'posts_per_page' => 10,
'meta_key' => ''.$meta_key.'',
'orderby' => ''.$orderby.'',
'order' => ''.$order.'',
'tax_query' => array(
array(
'taxonomy' => 'bedrijfs-category',
'field' => 'name',
'terms' => $category
)
),
'meta_query' => array(
array(
'key'=> ''.$key.'',
'value' => ''.$value.'',
'compare' => 'LIKE'
)
)
);
$the_query = new WP_Query($args); }
WHat i would like is a solution for inserting an empty variable in the meta_key => ''.$meta_key.'' so the loop skips the meta_key part.
define meta_query or tax_query out of $args
and (example):
if($_GET['some_name'] !== ''){
$meta_query = array(
array(
'taxonomy' => 'bedrijfs-category',
'field' => 'name',
'terms' => $category
)
);
//define args with some_one para exists
$args = array(
'post_type' => 'bedrijf',
'posts_per_page' => 10,
'meta_key' => ''.$meta_key.'',
'orderby' => ''.$orderby.'',
'order' => ''.$order.'',
'meta_query' => $meta_query
);
}else{
//define args with some_one para not exists
$args = array(
'post_type' => 'bedrijf',
'posts_per_page' => 10,
'meta_key' => ''.$meta_key.'',
'orderby' => ''.$orderby.'',
'order' => ''.$order.''
);
}
tax_query is like this

Woocommerce - get product in category with specific attribute

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.

Query WooCommerce Products based on Attribute

This one's driving me nuts.. I'm trying to query and output WooCommerce products based on a specific attribute. For example, I set up an Attribute called on, with possible values of yes or no.
I query using the following:
$args = array(
'post_type' => 'product',
'meta_key' => 'pa_on',
'meta_value' => 'yes',
'posts_per_page' => -1
);
query_posts($args);
The meta_key is crucial perhaps; if I call it on I get nothing. If I call it pa_on (because that's how I understand WooCommerce custom attributes to be constructed) I get nothing.
However, if I try a different query and use _featured, which is a standard WooCommerce custom meta thingy, it returns the relevant featured posts. Help, anyone?
I know this is an old one, but just in case someone stumbles upon it like I did today -- Woocommerce (I'm using v2.6.2) appears to store these custom attributes as taxonomies.
I suspect the correct args for the original question would look like this:
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'pa_on',
'field' => 'name',
'terms' => 'yes'
)
)
);
Using the appropriate values for my installation, it solved my problem.
For new woocommerce use:
$attribute = 'on';
$value = 'yes';
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'pa_' . $attribute,
'terms' => $value,
'field' => 'slug',
'operator' => 'IN'
)
)
);
If product attribute is saved as specific product attribute (i.e. not global), then you can't query it as taxonomy, instead you can use this snippet (copied from http://snippet.fm/snippets/query-woocommerce-products-product-specific-custom-attribute/):
// Set custom attribute name and value to search for
$attribute_name = 'color';
$attribute_value = 'green';
$serialized_value = serialize( 'name' ) . serialize( $attribute_name ) . serialize( 'value' ) . serialize( $attribute_value ); // extended version: $serialized_value = serialize( $attribute_name ) . 'a:6:{' . serialize( 'name' ) . serialize( $attribute_name ) . serialize( 'value' ) . serialize( $attribute_value ) . serialize( 'position' );
$args = array(
'post_type' => 'product',
'post_status' => 'any',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => '_product_attributes',
'value' => $serialized_value,
'compare' => 'LIKE',
),
),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) {
$loop->the_post();
// do stuff here... e.g. get_the_ID()
}
wp_reset_postdata();
Guess what you need is a query with meta_query value set:
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'pa_on',
'value' => 'yes',
'compare' => '='
)
)
);
$query = new WP_Query( $args );
You can learn more about those here:
http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

wordpress advanced custom fields order posts by date-picker

For those familiar with the ACF plugin...
I have some events posts that are currently displaying in post order (see code below). I would like them to display in the order specified by the date-picker.
Can anyone tell me what to amend in the following - I have tried the documentation on the site, but my PHP is basic.
It says I need to add
'orderby' => 'meta_value_num',
But no joy.
<?php function le_whatson_aside() {
//THis loop is for the CPT
$args = array(
'post_type' => 'events', // enter your custom post type
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page'=> '10', // overrides posts per page in theme settings
'tax_query' => array(
array(
'taxonomy' => 'audience', //name of custom taxonomy
'field' => 'slug',
'terms' => 'everyone' //name of category
)
)
);
$loop = new WP_Query( $args );
if( $loop->have_posts() ):
?>
<div>
<h2>What's On</h2>
</div>
<div class="whatson entry-content">
<?php
while( $loop->have_posts() ): $loop->the_post(); global $post;
?>
<p class="whatson-date"><?php echo date("dS F Y",strtotime(get_field('date')));?></p>
<h4 class="whatson-title"><?php echo get_the_title(); ?></h4>
<?php
endwhile;
?>
</div>
<?php
endif; }
Thanks all.
Try
orderby=date or `post_date`
If not the easiest way is to save your custom field 'startdate' as a unix timestamp. To do this, add the following to your theme's functions.php
// CREATE UNIX TIME STAMP FROM DATE PICKER
function custom_unixtimesamp ( $post_id ) {
if ( get_post_type( $post_id ) == 'events' ) {
$startdate = get_post_meta($post_id, 'startdate', true);
if($startdate) {
$dateparts = explode('/', $startdate);
$newdate1 = strtotime(date('d.m.Y H:i:s', strtotime($dateparts[1].'/'.$dateparts[0].'/'.$dateparts[2])));
update_post_meta($post_id, 'unixstartdate', $newdate1 );
}
}
}
add_action( 'save_post', 'custom_unixtimesamp', 100, 2);
The do:
$today = time();
$args = array(
'post_type' => 'events',
'posts_per_page' => 5,
'meta_query' => array(
array(
'key' => 'unixstartdate',
'compare' => '>=',
'value' => $today,
)
),
'meta_key' => 'startdate',
'orderby' => 'meta_value',
'order' => 'ASC',
);
$query = new WP_Query( $args );
$events = $query->posts;
Got it from here
I spent hours looking for this and I can confirm it works. See my code below.
If you're trying for a loop on a page with other loops, with a bunch of template parts in there, and you would also like to sort by a category, it goes :
$today = time();
$the_query = new WP_Query( array(
'post_type' => 'events',
'posts_per_page' => 3,
'meta_query' => array(
array(
'key' => 'start',
'value' => $today,
'compare' => '>=',
)
),
'tax_query' => array(
array (
'taxonomy' => 'the_taxonomy',
'field' => 'slug',
'terms' => 'the-name'
)
),
'meta_key' => 'start',
'orderby' => 'meta_value',
'order' => 'ASC',
) );
while ( $the_query->have_posts() ) :
$the_query->the_post();
get_template_part( 'content-events' );
endwhile;
wp_reset_postdata();
Of course, you have to include Unix the function beforehand.
function custom_unixtimesamp ( $post_id ) {
if ( get_post_type( $post_id ) == 'events' ) {
$startdate = get_post_meta($post_id, 'start', true);
if($startdate) {
$dateparts = explode('_', $startdate);
$newdate1 = strtotime(date('d.m.Y H:i:s', strtotime($dateparts[1].'/'.$dateparts[0].'/'.$dateparts[2])));
update_post_meta($post_id, 'unixstartdate', $newdate1 );
}
}
}
add_action( 'save_post', 'custom_unixtimesamp', 100, 2);
I would approach it like this. Create a "named" meta query and then order by that query. The meta query uses "EXITS" to filter out posts that don't have a date set. This works with the ACF date picker when the dates are saved to the database using the default format d/m/Y. This approach also works with the datetime picker.
$query = new WP_Query([
"meta_query" => [
"custom_date" => [
"key" => "date",
"compare" => "EXISTS",
"type" => "DATETIME",
]
],
"orderby" => [
"custom_date" => "ASC",
],
]);
Be sure to update the value for key to whatever your ACF field name is.

Resources