php – Blog posts not sorted and pagination not adjusted after filtering some category

Hello I’m really stuck and messed up now so I thought I’d try and ask the community.

I am working on a blog post page where I am showing some posts. The user has the choice to search for posts through a search form or to click on certain categories and filter the category. It works fine for now. But I couldn’t find a way to adjust pagination in this newly filtered post. Also the posts are not sorted after filtering.

I created a new Array where I loop through with no success. The posts are still in the same condition.

the former. User is filtering for outsourcing so all posts with category outsourcing are showing but they are split that means some posts are on page 1 some of them are on page 2 and so after filtering the array is not new sorted and they stick to those page positions:

Here’s my code which I then loop through and showing the HTML with the title, image etc… and some screenshots:

$searchBlog = '';
$searchCategory = '';
if(!empty($_GET['searchBlog']))
{
    $searchBlog = $_GET['searchBlog'];

}
if(!empty($_GET['search_category']))
{
    $searchCategory = $_GET['search_category'];
}

global $wp_query;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$categories = get_categories();

$args = array(
    'posts_per_page' => 5,
    'paged' => $paged,
    'post_type' => 'post',
    'order' => 'DESC',
);

$big = 999999999; // need an unlikely integer

$query = new WP_Query( $args );


$postsList = [];
foreach ($query->posts AS $post)
{
    $custom = get_post_custom($post->ID);
    $post_category = wp_get_post_categories($post->ID);
    foreach ($post_category AS $cat)
    {
        $postsList[] = [
                'post' => $post,
                'category' => $cat,
        ];
    }
}
$filteredPostList = [];
foreach ($postsList AS $posts) {
    if (!empty($searchCategory) && $posts['category'] == $searchCategory) {
        $filteredPostList[] = $posts;
        var_dump('category');
    } elseif (!empty($searchBlog) && str_contains(strtolower($posts['post']->post_title), strtolower($searchBlog))) {
        $filteredPostList[] = $posts;
        var_dump('search');
    } elseif (empty($searchCategory) && $posts['category'] != $searchCategory && empty($searchBlog)) {
        $filteredPostList[] = $posts;
        var_dump('all');
    }
}

$pagination = paginate_links( array(
    'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'format' => '/page/%#%',
    'current' => max( 1, get_query_var('paged') ),
    'total' => $query->max_num_pages,
    'prev_text'    => __('<i class="ico_arrow_left_black"></i>'),
    'next_text'    => __('<i class="ico_arrow_right_black"></i>'),
    'type' => 'list',
) );

Here is another page with more posts from the same category

Leave a Comment