I am trying to order my WordPress query by category ID but want to set the order statically.
below are the arguments that set the order:
'orderby' => 'ID',
'order' => 'ASC',
Is it possible to set the 'order' statically
like so:
'order' => '50,49,48,51',
I have tried using the post_in attribute but still am not seeing the order update:
$args = array(
'post_type' => $custom_post_type,
"$taxonomy" => $taxonomy_term->slug,
'post_status' => 'publish',
'post_in' => array(5,47,48,49,46,50),
'orderby' => 'post_in',
'posts_per_page' => 9999
);
function posts_orderby( $orderby ) {
global $wpdb;
$orderby = 'FIND_IN_SET(ID, "50,49,48,51")';
return $orderby;
}
add_filter('posts_orderby', 'posts_orderby');
Reading: Returning query results in predefined order
http://www.undolog.com/2012/03/13/wordpress-get_posts-e-orderby/
go for this plugin : "taxonomy-terms-order"
taxonomy-terms-order
thanks
Related
I've implemented an infinite scroll and in search results upon ordering by price or any custom value it doesn't work.
Here inside my enqueued script:-
isset($_GET['orderby'])?$ga_order_by = $_GET['orderby']: $ga_order_by = '';//grabbing the orderby value
if( gettype($result) == 'object') {
$ga_wp_query = new \WP_Query([ 'post_type'=> ['product_variation', 'product'], 'post__in' => $includes, 'orderby' => ['post__in',$ga_order_by], 'order' => 'ASC' ]);//so i'm ordering by search results and dynamically grabbed value.
} else {
$ga_wp_query = new \WP_Query([ 'post_type'=> 'product', 'post__in' => $includes, 'orderby' => ['post__in',$ga_order_by], 'order' => 'ASC']);
}
$args['ga_search_posts'] = json_encode($ga_wp_query->query_vars);
Inside my ajax handling function call upon search:-
$search_query = json_decode( stripslashes( $_POST['search_posts'] ), true );//this is the $args['ga_search_posts'] i'm posting via my javascript
$search_query['post_status'] = 'publish';
$search_query['posts_per_page'] = get_option('posts_per_page');
$search_query['paged'] = $_POST['page'] + 1;
wc_set_loop_prop( 'total', $_POST['search_count'] );
add_filter( 'woocommerce_get_price_html', 'labtag_show_price' );
ob_start();
query_posts( $search_query);
if ( have_posts() ) {//product loop
if ( wc_get_loop_prop( 'total' ) ) {
while ( have_posts() ) {
the_post();
wc_get_template_part( 'content', 'product' );
}
}
}
$data = ob_get_clean();
die($data);
exit;
This works except if I try to order by any parameter say price etc. Can't 'orderby' => ['post__in',$ga_order_by] declared like an array?If not should I be passing all my posts ids to the ajax handler iterate them and sort them (if this is the case, how to handle my custom order_by params)?
https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
So, with WordPress' OrderBy, you have a couple of different options.
If you want both parameters to be sorted in the same direction of ASC or DESC, then the argument anticipates a single string, with the parameters separated by a space.
Multiple 'orderby' values Display pages ordered by 'title' and
'menu_order'. (title is dominant):
$args = array(
'post_type' => 'page',
'orderby' => 'title menu_order',
'order' => 'ASC',
);
$query = new WP_Query( $args );
You use an array when you are sorting each parameter differently:
Multiple 'orderby' values using an array
> Display pages ordered by 'title' and 'menu_order' with different sort
> orders (ASC/DESC) (available since Version 4.0):
$args = array(
'orderby' => array( 'title' => 'DESC', 'menu_order' => 'ASC' )
);
$query = new WP_Query( $args );
In your case, since you are using a variable, consider building the string and then using this within your arguments array, i.e.:
//start with a space, then .= to concatenate the $_GET parameter with the space if it's set, or clear the string if it's not.
$ga_order_by = " ";
isset($_GET['orderby'])?$ga_order_by .= $_GET['orderby']: $ga_order_by = '';
//grabbing the orderby value and building our complete string.
$orderBy = 'post__in'.$ga_order_by;
if (gettype($result) == 'object') {
$ga_wp_query = new \WP_Query([ 'post_type'=> ['product_variation', 'product'], 'post__in' => $includes, 'orderby' => $orderBy , 'order' => 'ASC' ]);//so i'm ordering by search results and dynamically grabbed value.
} else {
$ga_wp_query = new \WP_Query([ 'post_type'=> 'product', 'post__in' => $includes, 'orderby' => $orderBy, 'order' => 'ASC']);
}
I have this code, its working good, but its gets posts from all categories. I need to get posts only from category ID 2. I tried to add "AND term_taxonomy_id = 2" to my code, but this didint work. Can somebody help me with this, my code:
<?php //loops all posts
$my_query = $wpdb->get_results
("SELECT * FROM `{$table_prefix}posts`, {$table_prefix}postmeta
WHERE {$table_prefix}posts.post_status = 'publish'
AND {$table_prefix}posts.id = {$table_prefix}postmeta.post_id
AND {$table_prefix}postmeta.`meta_key` = 'wpcf-data-nuo' ORDER BY if({$table_prefix}postmeta.`meta_value` = '' or {$table_prefix}postmeta.`meta_value` is null,1,0), {$table_prefix}postmeta.`meta_value` ASC LIMIT 12");
foreach($my_query as $post) {
setup_postdata($post);
?>
Please follow below code, Hope! its working
You can define the meta key for orderby parameter using the old method (I tested on WP 3.1.1)...
query_posts(
array( 'post_type' => 'services',
'order' => 'ASC',
'meta_key' => 'some_key',
'orderby' => 'meta_value', //or 'meta_value_num'
'meta_query' => array(
array('key' => 'order_in_archive',
'value' => 'some_value'
)
)
)
);
OR
For me, I wanted to order by a numeric field and I had to use 'type' => 'NUMERIC' inside the meta query.
This issue in general is cleared up in WordPress 4.2 by using named queries. e.g.
$args = array(
'post_type' => 'services',
'orderby' => 'order_clause',
'meta_query' => array(
'order_clause' => array(
'key' => 'order_in_archive',
'value' => 'some_value',
'type' => 'NUMERIC' // unless the field is not a number
)));
Reference link for set the meta value in query: https://rudrastyh.com/wordpress/meta_query.html
You can do it by WP_QUERY instead writing custom Query.
The query to get the results and then your custom sort order by altering the WP_QUERY if default order parameters not work as expected.
$args = array(
'post_type' => 'post',
'posts_per_page' => 8,
'cat' => 2,
'meta_key' => 'wpcf-data-nuo',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
add_filter('posts_orderby', 'filter_query');
$q = new WP_Query($args);
remove_filter('posts_orderby', 'filter_query');
function filter_query( $orderby_statement ) {
global $table_prefix;
$orderby_statement .= " if({$table_prefix}postmeta.`meta_value` = '' ";
$orderby_statement .= " or {$table_prefix}postmeta.`meta_value` is null,1,0), {$table_prefix}postmeta.`meta_value`";
return $orderby_statement;
}
Note: Do not remove spaces from $orderby_statement .= because it require spaces while running query.
If it still doesn't work, then add var_dump($orderby_statement); before return $orderby_statement; then copy the SQL and add it in your question so it will help us to understand what is the issue.
I got an array of orders ID's and 'post__in' => $orders_ids to embed them in a WP_Query:
$filters_orders = array(
'post_status' => 'processing',
'post_type' => 'shop_order',
'posts_per_page' => 10,
'post__in' => $orders_ids,
'orderby' => 'modified',
'order' => 'ASC'
);
$loop = new WP_Query($filters_orders);
while ($loop->have_posts()) {
$loop->the_post();
$order = new WC_Order($loop->post->ID);
<HERE_MY_CUSTOM_HTML_TABLE>
}
I am filtering "processing" order status only, but it doesn't work and I get all kind of status.
What I am doing wrong? How to filter order status correctly in this WP_Query?
In a WP_Query, you need to use the post_status slugs like in the database table wp_posts… All orders status start with "wc-":
So in your case: 'post_status' => 'wc-processing'.
This should work now.
I want to generate few random links for my wordpress but i don't want to use order by rand as it will cause heavy load on mysql. below links works fine but when i use orderby rand
$wprpi_arg = array(
'numberposts' => $wprpi_value['post'],
'post__not_in' => array(get_the_ID()),
// 'where ID <' => get_the_ID(),
'orderby' => 'rand',
'post_status' => 'publish',
);
i want to use this instead
$wprpi_arg = array(
'numberposts' => $wprpi_value['post'],
'post__not_in' => array(get_the_ID()),
'where ID <' => get_the_ID(),
'orderby' => 'ID',
'post_status' => 'publish',
);
But this is not working. WordPress is listing only 5 last links of table as it is orderby id its showing 5 links in desc order.
But i want to generate 5 links lower than my current id.
For example: if users is on page /10000 the generated links should be 9999,9998,9997,9996,9995 and if user is on /100 page generated links will be 99,98,97,96,95 but wordpress ignores where clause and generates same link always orderby desc limit 5 without considering where clause
You can use custom where condition in your wordpress query as below.
Note: Use get_the_ID() instead of 215 in your case
//Add Filter
add_filter( 'posts_where' , 'posts_where_for_ID' );
function posts_where_for_ID( $where ) {
$where .= ' AND ID < '. 215;
return $where;
}
//Create args
$args = array(
'numberposts' => 5, //$wprpi_value['post']
'post__not_in' => array(215),
'orderby' => 'ID',
'order' => 'DESC',
'post_status' => 'publish',
'suppress_filters' => FALSE
);
//Get the posts
$desc_posts = get_posts($args);
//Store post ids
$p_ids = array();
foreach($desc_posts as $posts_) {
$p_ids[] = $posts_->ID;
}
//Your ids are here
var_dump($p_ids);
This will applied to all get_posts() query in which suppress_filters passed in args.
If you have custom post_type then ckeck for post type or if you have single page then add in that page only.
I feel like I've been all around the web and back again looking for an answer to this and it's really starting to grind my gears.
Not sure if this is the correct way to do it, but I want to add a query_posts array to a URL in the form of a query_arg. This is our query:
query_posts( array( 'meta_key' => 'rank', 'orderby' => 'meta_value_num', 'order' => 'DESC' , 'paged' => $paged,
How do I use add_query_arg to pass that to the URL so as to re-order the posts with that meta_key/query_posts array?
I tried this, it doesn't seem to change the order of the posts, there's something I'm missing here.
Rank
<?php $by_rank= esc_url(add_query_arg(array('meta_key' => 'rank', 'orderby' => 'meta_value_num', 'order' => 'DESC'))); ?>
The reason I want to add the query vars to the URL string is so users can sort posts on category pages based on the meta_key/meta_value. Sort of in a similar way to doing ?orderby=date, except with a meta_key.
This can be done, right? Because I'm seriously starting to think it's not possible.
From Rahil's answer
<?php
$meta_key = (isset($_GET['meta_key'])) ?
sanitize_text_field($_GET['meta_key']) : 'rank'; // use default value here ''
$orderby = (isset($_GET['orderby'])) ?
sanitize_text_field($_GET['orderby']) : 'meta_value_num'; // use default value here ''
$order = (isset($_GET['order'])) ?
sanitize_text_field($_GET['order']) : 'DESC'; // use default value here ''
$by_rank = esc_url(add_query_arg(array(
'meta_key' => $meta_key,
'orderby' => $orderby,
'order' => $order
)));
?>
Rank
Put in the values, the same values that work fine with a query_posts array on other pages, posts don't re-order.
The answer:-
function wpse139657_orderby(){
if( isset($_GET['orderby']) ){
$order = $_GET['order'] or 'DESC';
set_query_var('orderby', 'meta_value_num');
set_query_var('meta_key', $_GET['orderby']);
set_query_var('order', $order);
}
}
add_filter('pre_get_posts','wpse139657_orderby');
Create a pre_get_posts filter and just pass the meta_key name to the URL like so ?orderby=rank
You are actually doing add_query_arg fine but echoing the variable before assigning it some value is your problem.
Rank
--------------------^^^^^^^^ ----->> undefined variable
<?php $by_rank= esc_url(add_query_arg(array('meta_key' => 'rank', 'orderby' => 'meta_value_num', 'order' => 'DESC'))); ?>
------^^^^^^^^ ----> Now its defined.
Change to this: (Remember Code runs from top to bottom)
<?php
$meta_key = (isset($_GET['meta_key'])) ?
sanitize_text_field($_GET['meta_key']) : ''; // use default value here ''
$orderby = (isset($_GET['orderby'])) ?
sanitize_text_field($_GET['orderby']) : ''; // use default value here ''
$order = (isset($_GET['order'])) ?
sanitize_text_field($_GET['order']) : ''; // use default value here ''
$by_rank = esc_url(add_query_arg(array(
'meta_key' => $meta_key,
'orderby' => $orderby,
'order' => $order
)));
?>
Rank
Now $by_rank has been assigned a value and you can echo it. It will output
/?meta_key=rank&orderby=meta_value_num&order=DESC
Edit:
Now you have to put above variables $meta_key, $orderby and $order to your query_posts() function:
Like this:
query_posts(array(
'meta_key' => $meta_key,
'orderby' => $orderby,
'order' => $order,
'paged' => $paged
));
Now changing query strings from url will affect the query_posts()