I have been through several topics on sorting taxonomies and custom fields, including some that were promising. However, I am still not constructing my query args correctly it seems.
I am "fixing" someone else's code in a custom theme that is used in a multisite configuration, but I am able to override/filter the query on a per-site basis.
The query is called via the theme with the following:
return apply_filters( 'theme_query_args_filter', $args);
I have custom fields in the "role" taxonomy that include:
last_name
first_name
Pretty common I think.
However, when the args are executed, the following filter args are sorting only by last name (key part is the else clause):
function my_args_filter( $args ) {
if (is_home() && !is_search()) {
$args['meta_key'] = 'event_date';
$args['orderby'] = 'event_date';
$args['order'] = 'DESC';
}
else {
$tax = $args['taxonomy'];
$theterm = $args['term'];
$args = array (
'taxonomy' => $tax,
'term' => $theterm,
'meta_key' => 'last_name',
'orderby' => 'meta_value',
'order' => 'ASC'
);
}
add_filter( 'theme_query_args_filter', 'my_args_filter' );
I've tried to modify the orderby as indicated in https://make.wordpress.org/core/2014/08/29/a-more-powerful-order-by-in-wordpress-4-0/ to use an array to do a multisort, but I'm hitting my head up against the wall. I think the problem is that the code is written using a mixture of old ways of doing things and new ways.
Any advice is appreciated. According to the example on in the docs above, I SHOULD be able to pass in multiple meta key/value/orders via an array, but I'm just not getting it.
Thanks for any leads you might have. (long-time listener, first-time caller)
(I also looked at https://wordpress.stackexchange.com/questions/109849/order-by-desc-asc-in-custom-wp-query but I couldn't extrapolate that example to this one either)
Figured it out on my most recent try. Hat tip to this solution https://wordpress.stackexchange.com/questions/249881/multiple-custom-fields-for-orderby-in-wp-query by Nath. if there is a more elegant way to do it, please let me know.
$tax = $args['taxonomy'];
$theterm = $args['term'];
$paged = $args['paged'];
$args = array (
'taxonomy' => $tax,
'term' => $theterm,
'paged' => $paged,
'posts_per_page' => '10',
'meta_query' => array(
array(
'relation' => 'AND',
'last_name' =>
array(
'key' => 'last_name',
'compare' => 'EXISTS',
),
'first_name' =>
array(
'key' => 'first_name',
'compare' => 'EXISTS',
),
),
),
'orderby' => array (
'last_name' => 'ASC',
'first_name' => 'ASC',
)
);
}
Related
I have a custom post type "product", and two custom taxonomies: "productfamily" and "industry".
On my single product page, I need to show products that are in the same productfamily and industry.
Some products might be in a few different industries...and my related products section only needs to match one of the industries of the current post to show up.
Here's what I have so far...
$wp_query = new WP_Query(
array(
'posts_per_page' => '4',
'post_type' => 'product',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'productfamily',
'field' => 'slug',
'terms' => $prodfam,
'operator' => 'IN'
),
array(
'taxonomy' => 'industry',
'field' => 'term_id',
'terms' => $prodindustry,
'operator' => 'IN'
),
),
'orderby' => 'title',
'order' => 'ASC',
)
);
If I change the "AND" relation to "OR", it seems to partly work by showing products from the same "productfamily", but doesn't seem to be taking the "industry" into account at all.
How can I get this to show related products based off of my two custom taxonomies please? Thanks in advance for your help.
As you described in comment that you have slugs array in variables but in one of your tax query condition, you've used term_id to match with slug. that is incorrect.
You can directly use the terms ids instead of slugs since it's dynamic things. in function wp_get_post_terms you can pass array( 'fields' => 'ids' ) as 3rd param and it will give you array of ids. so you don't have make an extra loop.
Then you'll have to check both terms array if they both are empty of one of them or both of them as values?
then you can check them individually and then add the tax query part if ids are available.
This is how you can write the code in a clean way with proper checks:
global $post;
// Get the terms ids array,
// we can pass 'fields' => 'ids' in 3rd param so we don't need to run the loop to collect ids.
$product_family_ids = wp_get_post_terms( $post->ID, 'productfamily', array( 'fields' => 'ids' ) );
$industry_ids = wp_get_post_terms( $post->ID, 'industry', array( 'fields' => 'ids' ) );
// Prepare query args.
$query_args = array(
'posts_per_page' => '4',
'post_type' => 'product',
'orderby' => 'title',
'order' => 'ASC',
'tax_query' => array(
'relation' => 'AND',
),
);
// We need to check if both ids are not empty.
// if both empty we don't wanna run query.
if ( ! empty( $product_family_ids ) || ! empty( $industry_ids ) ) {
// If product family terms are available.
if ( ! empty( $product_family_ids ) ) {
$query_args['tax_query'][] = array(
'taxonomy' => 'productfamily',
'field' => 'term_id',
'terms' => (array) $product_family_ids,
'operator' => 'IN',
);
}
// If industry terms are available.
if ( ! empty( $industry_ids ) ) {
$query_args['tax_query'][] = array(
'taxonomy' => 'industry',
'field' => 'term_id',
'terms' => (array) $industry_ids,
'operator' => 'IN',
);
}
$related_posts = new WP_Query( $query_args );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) {
$related_posts->the_post();
/**
* DO you thing here.
*/
}
}
wp_reset_postdata();
}
Note: I have not tested the code so there might be syntax errors, if you use the code and find errors after using the code please let me know so that I could fix errors in my answers. Also, Make sure you have site backup and FTP access to fix the errors, Don't add code from WordPress backend
I have two queries which I believed should both work because I believe they are exactly the same
The one is as follows ( Works perfectly, and gives me the posts I need )
$args2 = array(
'post_type' => 'vacancy',
'meta_key' => 'full_or_part_time',
'meta_value' => 'part_time',
)
The other one is as follow : ( Returns all posts, ignores the meta query )
$args2 = array(
'post_type' => 'vacancy',
'meta_query' => array(
array(
'key' => 'full_or_part_time',
'value' => "part_time",
)
),
);
I cannot figure out why option two does not work. Any assistance will be greatly appreciated.
I'm trying to figure out how to achieve a specific query to modify my search results for posts with WordPress. I'm trying to search via a custom field called "Common Authors".
There can be multiple Common authors, which is causing my query to sometimes fail. Here is what I've got for now:
<?php
...
$query->set('meta_key', 'common_authors');
$query->set('meta_value', serialize( array(strval($_GET['common_author'])))); // I get a single ID from the url as a string
$query->set('meta_compare', 'IN');
This is what I see when I var_dump the query:
'meta_key' => string 'common_authors'
'meta_value' => string 'a:1:{i:0;s:5:"17145";}'
This works fine if there is only one common_author.
However, there can be multiple common_authors for a post. Here is a meta_value example from the database:
a:4:{i:0;s:5:"14409";i:1;s:5:"17145";i:2;s:5:"14407";i:3;s:5:"14406";}
Could somebody help me out, to figure out how to adapt my query, so that it would return this one as well?
Try This One Work Prefect!
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'common_authors',
'value' => array ( 'author1', 'author2', 'author3' ),
'compare' => 'IN'
)
)
);
$query = new WP_QUERY($args);
if You Need To Use It In pre_get_posts
$meta_query = array(
array(
'key' => 'common_authors',
'value' => array ( 'author1', 'author2', 'author3' ),
'compare' => 'IN'
)
);
$query->set('meta_query', $meta_query);
I'm using the advanced custom fields plugin for wordpress to create a group of custom post types that have a date set within them.
I'm trying to show the previous post, and the next post, based on the date stored in the custom field. The links need to link to posts that have a date set in the future (so don't show links to posts with dates that have gone by)/
I can get a list of all the posts that are in the future, and out put these using the following code;
<?php
$rightnow = current_time('Ymd');
$args = array(
'post_type' => 'Courses',
'posts_per_page' => '25',
'meta_query' => array(
array(
'key' => 'date_of_the_course_single_day',
'compare' => '>=',
'value' => $rightnow,
)
),
'meta_key' => 'date_of_the_course_single_day',
'orderby' => 'meta_value',
'order' => 'ASC',
'post_status' => 'publish'
);
$posts = get_posts($args);
foreach ( $posts as $post ) {
?>
Output details of post here....
<?php
}
?>
What I thought I could do, is the get the current post's position in the array, to then get details of the posts one before and one after... but I haven't got a clue how to do this.
I've experimented with the wordpress next_post_link and previous_post_link functions, but these seem to work based on when the post was added to wordpress, rather than based on my custom date field.
Am I going about this the complete wrong way? Any tips or pointers would be much appreciated!
Use WP_Query plus paginate_links
$rightnow = current_time('Ymd');
// Query Args
$args = array(
'post_type' => 'Courses',
'posts_per_page' => '25',
'meta_query' => array( array(
'key' => 'date_of_the_course_single_day',
'compare' => '>=',
'value' => $rightnow,
) ),
'meta_key' => 'date_of_the_course_single_day',
'orderby' => 'meta_value',
'order' => 'ASC',
'post_status' => 'publish'
);
$query = new WP_QUery( $arg );
$posts = $query->get_posts();
// Paginate Args
$page_args = array(
'base' => 'your_custom_page_url'.'%_%', // Make sure you got this current depending on your setup
'format' => '/%#%', // requires pretty permalinks
'total' => $query->max_num_pages,
'current' => 0,
'prev_text' => __('«'),
'next_text' => __('»'),
);
foreach ( $posts as $post ) {
// Output
}
echo paginate_links( $page_args );
You have to verify that the base and format of paginate args are correct of it won't properly worked.
This should be simple, but I just can't pinned down a good example of the correct syntax to do this.
I want to filter my posts by the meta_queries but order them by the specified meta_key.
When I run the code as is it results an infinite loop. I only included the problem code the other code is your basic Loop code that the query_post runs in.
Also all the PHP variables are correct and are not the problem.
$args2 = array(
'meta_key' => '_count-views_all',
//'meta_value' => $id,
'orderby' => 'meta_value_num',
'order' => $sortOrder,
'posts_per_page' => 9,
'paged' => $paged,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'contributorid1',
'value' => $id,
'compare' => '='
),
array(
'key' => 'contributorid2',
'value' => $id,
'compare' => '='
)
)
);
$posts = query_posts($args2);
}
Here is another query that works completely without issue to cross reference. The two run on the same page but the are nested in an if else statement
$args1 = array(
//'meta_key' => 'contributorid1',
//'meta_value' => $id,
'order' => $sortOrder,
'orderby' => 'title',
'posts_per_page' => 9,
'paged' => $paged,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'contributorid1',
'value' => $id,
'compare' => '='
),
array(
'key' => 'contributorid2',
'value' => $id,
'compare' => '='
)
)
);
$posts = query_posts($args1);
The query looks reasonable to me. The only method by which I see this running into an infinite loop is if this query runs within the post loop. When you use query_posts as you are, it will change the state of the global $wp_query, which is used for the pointer in the main posts loop.
If it kept hitting query_posts within the loop, it would continually change the state of the global $wp_query object, and reset the pointer for the current post to the first post of that new query, which would ultimately create the infinite loop.
If this code is being used within the loop, I'd recommend instead using something like
$query = new WP_Query($args2);
if ($query->have_posts()) { ... etc; }
If you need to then set up global post data within it, be sure to use wp_setup_postdata or $query->the_post() and wp_reset_postdata or wp_reset_query appropriately when you are finished using that post as the global post information.