0

My code works fine if user login but not work when log out

functions.php

//ajax search --
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){

    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'POST',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });

}
</script>

<?php
}
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
    $the_query = new WP_Query( array( 'posts_per_page' => 5, 's' => esc_attr( $_POST['keyword'] ) ) );
    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post(); ?>

            <div class="post-box-search">
              <a href="<?php echo esc_url( post_permalink() ); ?>">
                <?php the_post_thumbnail( 'index_post' );  ?>
                <h3><?php the_title();?></h3>
              </a>
            </div>

        <?php endwhile;
        wp_reset_postdata();
    endif;
    die();
}





 ?>

1 Answer 1

0

Try to output the debug query

Find fragment

$the_query = new WP_Query( array( 'posts_per_page' => 5, 's' => esc_attr( $_POST['keyword'] ) ) );
if( $the_query->have_posts() ) :

Replaced by

$the_query = new WP_Query( array( 'posts_per_page' => 5, 's' => esc_attr( $_POST['keyword'] ) ) );
echo (string)$the_query->request; 
if( $the_query->have_posts() ) :

Perhaps some hooks are triggered to find a guest. i checked - your code is working

1
  • Thank you for posting this code, but unfortunately it crashed completely and did not work.
    – mohammad
    Commented Sep 27, 2020 at 14:43

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.