I have a code in function.php
for showing pagination in a custom theme index page but it shows two errors in same line $wp_query
-
Undefined variable: wp_query in function.php
-
Trying to get property of non-object in function.php
my function:
function getpagenavi(){
?>
<div id="pagination" class="clearfix">
<?php
if (function_exists('wp_pagenavi')): ?>
<?php
wp_pagenavi() ?>
<?php else : ?>
<div class="alignleft">
<a href="<?php $max = $wp_query->max_num_pages; previous_posts();?>" class="classname" title="Previous post">Previous post</a></div>
<div class="alignright"><a href="<?php next_posts($max);?>" class="classname" title="Next post">Next post</a></div>
<div class="clear"></div>
<?php
endif; ?>
</div>
<?php
}
What can I do to correct this error?
You’re using
$wp_query->max_num_pages
when$wp_query
is not defined within that function scope.Pretending you know what
wp_query
is supposed to be at the point where that function is called, you can add the following line at the top of thegetpagenavi
function:or better, pass it as a parameter:
Make
WP_Query
as a global variable: