0

I have around 250+ blog posts and currently in my custom theme I've implemented the functionality of showing the blogs with pagination option. But in all pages it is showing the same posts.

<?php
$data = getData();

if(!empty($_REQUEST['posts'])){
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 15,
        'category_name' => $_REQUEST['posts'],
    );
    
}else{
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 15,
    );
}


$loop = new WP_Query($args);


?>

<style>

</style>
<div class="blog_main" data-aos="fade-up" data-aos-duration="500">
    <div class="container">
        <div class="filter-items">
            <div class="items">
                <div class="item <?php if(empty($_REQUEST['posts'])){echo 'active';} ?>">
                    <a href="<?php echo site_url('/blog')?>">Alla</a>
                </div>
                <div class="item <?php if($_REQUEST['posts'] == 'Blogg'){echo 'active';} ?>">
                    <a href="<?php echo site_url('/blog?posts=Blogg')?>">Blogg</a>
                </div>
                <div class="item <?php if($_REQUEST['posts'] == 'Nyheter'){echo 'active';} ?>">
                    <a href="<?php echo site_url('/blog?posts=Nyheter')?>">Nyheter</a>
                </div>
            </div>
        </div>
       
            <?php if ($loop->have_posts()) { ?>
                <div class="blog-container">
                    <?php while ($loop->have_posts()): $loop->the_post(); ?>
                        <div class="single-blog">
                            <a class="feature-image" href="<?php the_permalink()?>">
                                <?php echo get_the_post_thumbnail($post->ID, 'full') ? get_the_post_thumbnail($post->ID, 'full') : '<img loading="lazy" width="582" height="280" src="'.site_url( 'wp-content/uploads/2023/04/anse_lazio_stranden.jpeg' ).'" >' ?>
                            </a>
                            <div class="tags">
                                <span class="entry-date"><?php echo get_the_date(); ?></span>
                                <?php 
                                
                                $categories = get_the_category();
                                if ( ! empty( $categories ) ) {
                                    echo '<a href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a>';
                                }

                                ?>
                                <!-- <a href="">Nyheter</a> -->
                            </div>

                            <div class="title-section">
                                <a href="<?php the_permalink()?>">
                                    <h2><?php the_title()?></h2>
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M7 17L17 7" stroke="#1D2635" stroke-width="2" stroke-linecap="round"
                                            stroke-linejoin="round" />
                                        <path d="M7 7H17V17" stroke="#1D2635" stroke-width="2" stroke-linecap="round"
                                            stroke-linejoin="round" />
                                    </svg>
                                </a>

                            </div>
                        </div>
                    <?php endwhile;?>
                </div>
                <div class="pagination">
                    <a href="<?php 
                    if(max( 1, get_query_var( 'paged' ) ) == 1) { 
                        echo "javascript:void(0)";
                        $active = "";
                    }else
                    {
                        echo site_url('/blog/page/'.(get_query_var( 'paged' )-1).'?posts='.get_query_var( 'posts' ));
                        $active = "active";
                    }
                    ?>" class="preview <?php echo $active;?>">Tidigare</a>
                                <?php 
                            echo paginate_links( array(
                                'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
                                'total'        => $loop->max_num_pages,
                                'current'      => max( 1, get_query_var( 'paged' ) ),
                                'format'       => '?paged=%#%',
                                'show_all'     => false,
                                'type'         => 'list',
                                'end_size'     => 2,
                                'mid_size'     => 1,
                                'prev_next'    => false,
                                'prev_text'    => sprintf( '<i></i> %1$s', __( 'Tidigare', 'text-domain' ) ),
                                'next_text'    => sprintf( '%1$s <i></i>', __( 'Nästa', 'text-domain' ) ),
                                'add_args'     => false,
                                'add_fragment' => '',
                            ) );
                        ?>
                            <a href="<?php 
                                        if(max( 1, get_query_var( 'paged' ) ) > 1) {
                                            echo "javascript:void(0)";
                                            $active = "";
                                        }else
                                        {
                                            echo site_url('/blog/page/'.(get_query_var( 'paged' )+1).'?posts='.get_query_var( 'posts' ));
                                            $active = "active";
                                        }
                                        ?>" <?php echo max( 1, get_query_var( 'paged' ) ); ?> class="next <?php echo $active;?>">Nästa</a>
                </div>

            <?php } ?>

   
        
   
    </div>
</div>

How do I fix this so that each page shows items as per the page number and number of items.

4
  • is this on a page template or on your homepage? At no point is the query argument setting the current page so it will always default to the first, but if this is a homepage or blog archive then there's no reason to use WP_Query, pre_get_posts would be much faster and efficient, it's even possible this could be done entirely by appending ?category_name=xyz to the URL instead of using ?posts=, which is something WP already supports out of the box
    – Tom J Nowell
    Commented Oct 3, 2023 at 13:54
  • so this is on the blog page that was created in the custom theme template. I even tried the built in solution for pagination which is the_posts_pagination(). It didn't work @TomJNowell
    – buzz
    Commented Oct 4, 2023 at 5:55
  • the core problem is that those pagination functions are for the main query, but you've discarded the main query and created a brand new custom bespoke second query that does its own thing using new WP_Query, and the pagination functions are totally unaware of this. In addition, your new query has no concept of pagination, it's been told to use 15 posts per page, but at no point is it ever told which page it's on, the paged parameter is completely missing. Unfortunately the secondary query method doubles the cost of the page.
    – Tom J Nowell
    Commented Oct 4, 2023 at 9:49
  • @TomJNowell so what solution will you be advising here? I'm totally lost on how to solve this
    – buzz
    Commented Oct 4, 2023 at 11:08

1 Answer 1

0

After digging for sometime I've managed to solve it. The issue was I wasn't passing paged variable in the args. After passing it and tweaking the pagination logic it is working now.

<?php
$data = getData();

if(!empty($_REQUEST['posts'])){
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 15,
        'category_name' => $_REQUEST['posts'],
        'paged' => $paged
    );
    
}else{
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 15,
        'paged' => $paged
    );
}


$loop = new WP_Query($args);


?>

<style>

    /* Style for the disabled class */
.disabled {
    background-color: #ccc; /* Gray background color */
    color: #888 !important; /* Light gray text color */
    cursor: not-allowed; /* Change cursor to 'not allowed' */
    pointer-events: none; /* Make the button unclickable */
}

.blog_main .pagination .next, .blog_main .pagination .preview  {
    color: #000;
}

</style>
<div class="blog_main" data-aos="fade-up" data-aos-duration="500">
    <div class="container">
        <div class="filter-items">
            <div class="items">
                <div class="item <?php if(empty($_REQUEST['posts'])){echo 'active';} ?>">
                    <a href="<?php echo site_url('/blog')?>">Alla</a>
                </div>
                <div class="item <?php if($_REQUEST['posts'] == 'Blogg'){echo 'active';} ?>">
                    <a href="<?php echo site_url('/blog?posts=Blogg')?>">Blogg</a>
                </div>
                <div class="item <?php if($_REQUEST['posts'] == 'Nyheter'){echo 'active';} ?>">
                    <a href="<?php echo site_url('/blog?posts=Nyheter')?>">Nyheter</a>
                </div>
            </div>
        </div>
       
            <?php if ($loop->have_posts()) { ?>
                <div class="blog-container">
                    <?php while ($loop->have_posts()): $loop->the_post(); ?>
                        <div class="single-blog">
                            <a class="feature-image" href="<?php the_permalink()?>">
                                <?php echo get_the_post_thumbnail($post->ID, 'full') ? get_the_post_thumbnail($post->ID, 'full') : '<img loading="lazy" width="582" height="280" src="'.site_url( 'wp-content/uploads/2023/04/anse_lazio_stranden.jpeg' ).'" >' ?>
                            </a>
                            <div class="tags">
                                <span class="entry-date"><?php echo get_the_date(); ?></span>
                                <?php 
                                
                                $categories = get_the_category();
                                if ( ! empty( $categories ) ) {
                                    echo '<a href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a>';
                                }

                                ?>
                                <!-- <a href="">Nyheter</a> -->
                            </div>

                            <div class="title-section">
                                <a href="<?php the_permalink()?>">
                                    <h2><?php the_title()?></h2>
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M7 17L17 7" stroke="#1D2635" stroke-width="2" stroke-linecap="round"
                                            stroke-linejoin="round" />
                                        <path d="M7 7H17V17" stroke="#1D2635" stroke-width="2" stroke-linecap="round"
                                            stroke-linejoin="round" />
                                    </svg>
                                </a>

                            </div>
                        </div>
                    <?php endwhile;?>
                </div>
       
    <div class="pagination">
    <?php
            $total_pages = $loop->max_num_pages;
            $current_page = max(1, get_query_var('paged'));

            $base_url = site_url('/blog');
            if (!empty($_REQUEST['posts'])) {
                $base_url .= '?posts=' . $_REQUEST['posts'];
            }

            $prev_page = ($current_page > 1) ? $current_page - 1 : 1;
            $next_page = ($current_page < $total_pages) ? $current_page + 1 : $total_pages;

            $prev_url = ($prev_page == 1) ? $base_url : add_query_arg('paged', $prev_page, $base_url);
            $next_url = ($next_page == $total_pages) ? $base_url : add_query_arg('paged', $next_page, $base_url);

            // Add CSS classes and disable buttons
            $prev_class = ($current_page == 1) ? 'disabled' : '';
            $next_class = ($current_page == $total_pages) ? 'disabled' : '';

            echo '<a href="' . esc_url($prev_url) . '" class="preview ' . $prev_class . '">Tidigare</a>';
            echo paginate_links(
                array(
                    'base' => str_replace(999999999, '%#%', esc_url(get_pagenum_link(999999999))),
                    'total' => $total_pages,
                    'current' => $current_page,
                    'format' => '?paged=%#%',
                    'show_all' => false,
                    'type' => 'list',
                    'end_size' => 2,
                    'mid_size' => 1,
                    'prev_next' => false,
                    'prev_text' => sprintf('<i></i> %1$s', __('Tidigare', 'text-domain')),
                    'next_text' => sprintf('%1$s <i></i>', __('Nästa', 'text-domain')),
                    'add_args' => false,
                    'add_fragment' => '',
                )
            );
            echo '<a href="' . esc_url($next_url) . '" class="next ' . $next_class . '">Nästa</a>';
            ?>
        </div>


        <?php } ?>

     </div>
</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.