Custom theme show Notice Undefined variable: wp_query in function.php

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

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?

Related posts

Leave a Reply

2 comments

  1. 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 the getpagenavi function:

    Global $wp_query;
    

    or better, pass it as a parameter:

    // where you call the function assuming $wp_query exists there.
    getpagenavi($wp_query);
    
    // your function
    function getpagenavi($wp_query){