This is my HTML:

<input type="text" class="keyword" name="keyword" id="keyword" placeholder="Search video...">
<button id="search-keyword">Search</button>

When I click the "Search" button start a script like this:

    action = 'my_create_posts_search'; //php function to do 
    ab = document.getElementsByClassName('keyword')[0].value; //get the value of input

Then an Ajax function starts:

    type: "POST",
    url: ajax_params.ajax_url, //wordpress ajax
    data: {
     'action': action, //php function to do  
     'ab': ab, //value of input

Then the action start and the code excecuted is this:

function my_create_posts_search($name) {
 //Pagination for posts
 $response = '';
 $paged = (int) (!is_null($_POST['clicked_times'])) ? $_POST['clicked_times'] : 0;

 $postsPerPage = 18;
 $postOffset = $paged * $postsPerPage;

 $args = array(
    'posts_per_page'  => $postsPerPage, //pagination
    'offset'          => $postOffset, //pagination
    'category'        => 42, //post category
    's'               => $name, //value of input
    'orderby'         => 'date',
    'order'           => 'DESC',
 ... other things...

Everything works perfectly expcet when I would like to search by Post Tags.

How can I implement this feature?

I hope my code will help you. Thanks!


If you are using WP_Query you can search for tags using this code:

$query = new WP_Query( array( 'tag' => 'cooking' ) );

For more tag options see this page: https://developer.wordpress.org/reference/classes/wp_query/#tag-parameters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.