custom wp_query where meta_key is variable or not needed - wordpress

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

Related

WooCommerce get all products with SKU

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 */

Wordpress query adding 0=1 in wp_query and result dissappear

Wp query adding 0=1 in the query and results disappear, I am trying to adding multiple taxonomies in the query but it is producing 0=1. I am trying to fetch results from multiple taxonomies and in case of all I am passing a blank array to get all results
$category = array('');
$post_regions = array('');
$post_tag = array('');
$post_categories = array('');
if($_POST['pageType'] !== "all"){
$category = array (
'taxonomy' => 'category',
'field' => 'slug',
'operator' => 'IN',
'terms' => explode(',', $_POST['pageType'])
);
}
if($_POST['regions'] !== "default"){
$post_regions = array(
'taxonomy' => 'post_regions',
'field' => 'slug',
'operator' => 'IN',
'terms' => explode(',', $_POST['regions'])
);
}
if($_POST['topics'] !== "All"){
$post_tag = array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => explode(',', $_POST['topics']),
'operator' =>'IN'
);
}
$args = array(
'post_type' => 'post',
'orderby' => 'publish_date',
'posts_per_page' => -1,
'order' => 'DESC',
'post_status' => 'publish',
'date_query' => array(
'relation' => 'OR',
$dates
),
'tax_query' => array(
'relation' => 'AND',
$category,
$post_regions,
$post_tag,
$post_categories,
),
);
$query = new WP_Query( $args );
Define the empty array like this:
array();
If you define a array the way you do:
array('');
then array[0] is set.
Regards Tom
Adding variable exists check outside arguments work for me:
$args = array(
'post_type' => 'post',
'orderby' => 'publish_date',
'posts_per_page' => -1,
'order' => 'DESC',
'post_status' => 'publish',
'date_query' => array(
'relation' => 'OR',
$dates
),
'tax_query' => array(
'relation' => 'AND'
),
);
if (isset($category))
$args['tax_query'][] = $category;
if (isset($post_regions))
$args['tax_query'][] = $post_regions;
if (isset($post_tag))
$args['tax_query'][] = $post_tag;
if (isset($post_categories))
$args['tax_query'][] = $post_categories;
$query = new WP_Query( $args );
Because 0=1 evaluates to FALSE, and your entire AND clause is discarded, leaving the entire expression to be relied on the value of the OR clause
There is a block of code who design this SQL return.
In the class class-wp-query.php at line 2106
if ( ! $this->is_singular ) {
$this->parse_tax_query( $q );
$clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
$join .= $clauses['join'];
$where .= $clauses['where'];
}
this return 0=1.... for me

WP_Query based on excerpt content

Trying to pull post type according to their excerpt value.
my code so far:
$ids = array(111,333,9061);
$args = array (
'post_type' => 'kb',
'posts_per_page' => -1,
'meta_query' => array (
array(
'key' => 'excerpt',
'value' => $ids,
'compare' => 'IN'
)
)
);
$the_query = new WP_Query( $args );
If I remove the meta_query it pulls the posts.
Also tried with 'key' => 'post_excerpt'
Any ideas?

Order by post_meta in wp_query wordpress not working

I want to order posts by price in wordpress, I tried a lot and also concerned by documentation, all looks good but still it is not working..
here is code....
global $wp_query;
$query_vars = $wp_query->query_vars;
$post_per_page = 12;
global $term;
$term = (strip_tags($_GET['term']));
if (!empty($_GET['term'])) {
add_filter('posts_where', 'taskerdev_posts_where');
}
$meta_query = array();
$closed = array(
'key' => 'closed',
'value' => "0",
'compare' => '='
);
$meta_query[] = $closed;
if (!empty($_GET['tasker_cat_cat']))
$tasker_cat = array(
'taxonomy' => 'tasker_cat',
'field' => 'slug',
'terms' => $_GET['tasker_cat_cat']);
$meta_query[] = $tasker_cat;
$price = array(
'meta_key' => 'price',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
$meta_query[] = $price;
$args = array('post_type' => 'shoping', 'posts_per_page' => 10,
'paged' => $query_vars['paged'], 'meta_query' => $meta_query);
This code looks fine, but I cant get post order by price that is in post_meta..
I can see this code to sort results every where even in documentation of wp_query.
$price = array(
'meta_key' => 'price',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
$meta_query[] = $price;
are you sure that the metafield price is numeric?
'orderby' => 'meta_value_num',
works only on numeric fields.. if a value is numeric depends on the format of price saved in your field.
maybe post a example value so that people see what the real value is

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

Resources