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()
Related
So I have on my WordPress site a user page via a template.
the users are loaded via a custom post type called members.
now I have this part to display the users on a template page.
but I need it to be in alphabetical order
the code I have is as follows
TEMPLATE:
$member_type = (isset($member_type) ? $member_type : 'seb');
$post_type = $member_type == 'seb' ? array('companies', 'members') : 'companies';
// prepare arguments
$args = array(
'post_type' => 'members',
'orderby' => 'name',
'order' => 'ASC',
'post_status' => 'publish',
);
// create a query based on arguments
$query = new WP_Query($args);
while ($query->have_posts()):
$query->the_post();
plus I have:
<section>
<p>
<?php echo (get_field('title') ? get_field('title') . ' ' : '') ?>
<?php the_field('contactperson') ?>
</p>
</section>
with 'contactperson' being the member being called up and displayed
so how do I put the output of contact person in alphabetical order
I am assuming you are using Advanced Custom Fields, but any custom field manager plugin applies. Here is an explanation from the ACF website: https://www.advancedcustomfields.com/resources/orde-posts-by-custom-fields/
Bottomline: you need to order by the meta value of your meta key, "contactperson".
$args = array(
'post_type' => 'members',
'meta_key' => 'contactperson',
'orderby' => 'meta_value',
'order' => 'ASC',
'post_status' => 'publish',
);
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've set up a search query like this:
<?php
$s = get_search_query();
$args = array(
'post_type' => array('post'),
'posts_per_page' => '10',
'order' => 'DESC',
'orderby' => 'date',
's' => $s,
'paged' => $paged
);
$query_search = new WP_Query($args);
if ($query_search->have_posts())
{
while ($query_search->have_posts())
{
$query_search->the_post();
}
}
wp_reset_postdata();
?>
It works great, except when I'm searching for a post that contains punctuation in the title. For example, if the title is "Mark's Book" using "mark's" and "marks" both return no results.
If I just search "mark" it will come up, but I want either of the above keywords to also retrieve the post.
Is there something simple I'm missing as far as making this compatible with punctuation?
default get_search_query() pass through data on esc_attr() to ensure that it is safe for placing in an html attribute. if you want to off esc_attr() then try this code,
$s = get_search_query( false );
may be it'll help you
You can try this in this way:
$s = get_query_var('s');
$s = addslashes($s); //<-- even if you remove this the query will work
$args = array(
'post_type' => array('post'),
'posts_per_page' => '10',
'order' => 'DESC',
'orderby' => 'date',
's' => $s,
'paged' => $paged
);
$query_search = new WP_Query($args);
print_r($query_search->posts);
Please Note: I have assumed the query string is accessed by s.
Code is tested and works.
Hope this helps!
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