Unable to call search term in functions.php from s

2019-08-17 04:44发布

问题:

I am not able to call the search term in functions.php file from search.php file. I am trying to achieve this through the use of script.

$search_term should be called but it is not being called. If I replace it with certain keywords, posts shows perfectly. I want to call search term input by user using the search form.

search.php

<?php $search_query = get_search_query(); ?>
<div align="center">
<h2>Search Results For "<?php echo $search_query ?>"</h2>
</div>

<div class="entry-content" style="margin:2% 0 0 0;">
<?php if (have_posts()) : ?>
<div class="col-lg-12 col-md-12 col-sm-12 my-posts" style="padding:0 1% 1% 1%;">
<?php while (have_posts()) : the_post(); ?>
<?php 
echo "<div>";
This Part Shows Content
echo "</div>";
?>
<?php endwhile ?>
</div>
<?php endif ?>
</div>
<div class="loadmore" style="text-align:center;font-size:1.4em;color:#4a235a;padding:1% 0 1% 0;font-weight:900;">
<button type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;">Load More Posts</button>
</div>

<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore', function() {

    var data = {
        'action': 'load_posts_by_ajax_search',
        'page': page,
        'searchTerm': $('#s').val(),
        'security': '<?php echo wp_create_nonce("load_more_posts_search"); ?>'
    };

    $.post(ajaxurl, data, function(response) {
        $('.my-posts').append(response);
        page++;
    });
});
});

</script>

functions.php

add_action('wp_ajax_load_posts_by_ajax_search', 'load_posts_by_ajax_callback_search');
add_action('wp_ajax_nopriv_load_posts_by_ajax_search', 'load_posts_by_ajax_callback_search');

function load_posts_by_ajax_callback_search() {
check_ajax_referer('load_more_posts_search', 'security');
$paged_search = $_POST['page'];
$search_term = esc_attr($_POST['searchTerm']);
$args_search = array(
'posts_per_page' => '20',
's' => $search_term,
'paged' => $paged_search,
);
$my_posts_search = new WP_Query( $args_search );
if ( $my_posts_search->have_posts() ) :
    ?>
    <?php while ( $my_posts_search->have_posts() ) : $my_posts_search->the_post() ?>

<?php
echo "<div>";
This Part Shows Content
echo "</div>";
?>
<?php endwhile ?>
<?php endif; ?>

My searchform.php code

<form method="get" id="searchform" action="<?php bloginfo('url'); ?>" target="_self">
<div>
<input style="text-align:center;width:100%;margin:0 0 12px; 0;border-color:#4a235a;color:#000000;" placeholder='Eg:Location,Skill,Company' class="text" type="text" value="" name="s" id="s" />
</div> 
<div>
<input type="submit" style="text-align:center;margin:0 0 0 0;width:100%;border:1.5px solid;border-color:grey;background-color:#4a235a;color:#f4511e;" class="submit button" name="submit" value="<?php _e('Search');?>" />
</div>
</form>