Search results with pagination not working

Question

I’ve got a news page with a search bar functionality. On this page I want a user to be able to enter a term and the contents of that page will be updated depending on what the user has entered. I don’t have a search.php and I currently have it working on my news page. Here is my code

<form method="post" action="<?php echo esc_url(get_permalink()); ?>">
    <input type="text" name="search" autocomplete="off" value="<?php if(isset($_POST['search'])){print $_POST['search'];} ?>">
    <input type="submit" value="search our site">
</form>

<?php 
    $i = 0;
    global $the_query;
    $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;

    if(isset($_REQUEST['search'])){
        $args = array(
            'post_type' => '',
            's' => $_REQUEST['search'],
            'posts_per_page' => 1,
            'order' => 'DESC',
            'paged' => $paged
        );
        $the_query = new WP_Query( $args );
    } else {
        $args = array(
            'post_type' => '',
            'posts_per_page' => 1,
            'order' => 'DESC',
            'paged' => $paged
        );
        $the_query = new WP_Query( $args );
    }
    if ($the_query->have_posts()):
    while ($the_query->have_posts()) : $the_query->the_post(); 
    $i++;  
    $newsFields = get_fields();
?>

<?php if ($i % 2 == 0) { ?>
<section>
    <?= the_title(); ?>
    <?= the_excerpt();?>
</section>
<?php } else { ?>

<section>
<?= the_title(); ?>
<?= the_excerpt();?>
</section>
        
<?php } ?>

<?php
endwhile; ?>
<div class="pagination">
    <?php 
        echo paginate_links( array(
            'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
            'total'        => $the_query->max_num_pages,
            'current'      => 'current' => max( 1, get_query_var('paged') ),
            'format'       => '?paged=%#%',
            'show_all'     => false,
            'type'         => 'plain',
            'end_size'     => 2,
            'mid_size'     => 1,
            'prev_next'    => true,
            'prev_text'    => sprintf( '<i></i> %1$s', __( 'Previous', 'text-domain' ) ),
            'next_text'    => sprintf( '%1$s <i></i>', __( 'Next', 'text-domain' ) ),
            'add_args'     => false,
            'add_fragment' => '',
        ) );
    ?>
</div>

However, I am facing an issue with my pagination. Once I enter a term and the page is updated with posts related to that term and I hit the next page this gets refreshed and all posts are retrieved again. I’ve Looked and read through other posts to see if I could fix it but still nothing. Any help would be greatly appreciated

0
vllnv 8 months 2020-12-10T11:10:28-05:00 0 Answers 6 views 0

Leave an answer

Browse
Browse