This is my first question on stackoverflow.
I have problem with sorting posts. I write small plugin to sort posts alphabetically. It's work ok. There is a code:
function wpb_custom_query( $query ) {
if( $query->is_main_query() AND !($query->is_home()) ) {
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'wpb_custom_query' );
and Query Monitor see query as:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
LEFT JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE 1=1
AND ( wp_term_relationships.term_taxonomy_id IN (133,134,135,136,137,161) )
AND ((wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish'
OR wp_posts.post_status = 'private')))
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_title ASC
LIMIT 0, 70
But now I need change order posts by current category when user is. I try it change it by adding "if" conditions when I check what category is currently loaded and get category name, next check if category name is euqal "NEWSY". Code after modify:
function wpb_custom_query( $query ) {
if( $query->is_main_query() AND !($query->is_home()) ) {
$current_category = get_queried_object();
if($current_category->name == 'NEWSY')
{
$query->set( 'orderby', 'date' );
$query->set( 'order', 'DESC' );
}
else
{
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
}
}
}
add_action( 'pre_get_posts', 'wpb_custom_query' );
and Query Monitor see query as:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
LEFT JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE 1=1
AND ( wp_term_relationships.term_taxonomy_id IN (133) )
AND ((wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish'
OR wp_posts.post_status = 'private')))
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_title ASC
LIMIT 0, 70
It works when i go to categories named "NEWSY" but problem is in parent category (133) where all posts dissapears. I don't have posts adding to parent category, all posts is assigned to child categories. It depenced by another plugin when i set permissions by category for users. In Query Monitor I see that in query condition "wp_term_relationships.term_taxonomy_id" has only a parent category (133) and child categories dissapear. I don't know why it remove all chils categories from query.
I need help to fix this problem to see posts in parent categories back and still change sort order by category name.
I will be grateful for your help.