0

i am new to wordpress and i am learning paging the posts but the code below isnt working and i cant find whats wrong. please help.

the code:

<?php
$temp = $wp_query;
$wp_query= null;
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$wp_query = new WP_Query( 'posts_per_page=2&paged='.$paged );
while ( $wp_query->have_posts() ) : $wp_query->the_post();
?>
<h2>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</h2>
<?php the_excerpt(); ?>
<?php endwhile; ?>
<div class="navigation">
<div class="alignleft"><?php previous_posts_link( '&laquo; Previous' ); ?></div>
<div class="alignright"><?php next_posts_link( 'More &raquo;' ); ?></div>
</div>

<?php
$wp_query = null;
$wp_query = $temp;
?>

the error

Call to a member function get() on null in /var/www/html/wordpress/wp-includes/query.php on line 28

1 Answer 1

2

You are setting null to $wp_query then querying get_query_var( 'paged' ) this is expected that you will get this error!

First query get_query_var( 'paged' ) then set the original $wp_query to null

Example:-

$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

global $wp_query;
$temp = $wp_query;

$wp_query = new WP_Query( 'posts_per_page=2&paged='.$paged );

while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
    <h2>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </h2>
    <?php the_excerpt(); ?>
<?php endwhile; ?>
<div class="navigation">
<div class="alignleft"><?php previous_posts_link( '&laquo; Previous' ); ?></div>
<div class="alignright"><?php next_posts_link( 'More &raquo;' ); ?></div>
</div><?php

wp_reset_postdata();

$wp_query = $temp;

NOTE: Do not forgot to add wp_reset_postdata() after loop.

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.