Bespoke search functionality using AJAX and tags in WordPress

I have created a custom search form in my WordPress theme that looks like this:

<form role="search" class="form" method="get" action="<?php echo home_url('/');?>">
  <input type="search" id="keyword" class="inp-search" onclick="showNewTag()" oninput="searchTags()" onkeyup="fetch()" placeholder="search by tag" value="<?php echo get_search_query() ?>" name="s" title="Search" />

However, I am currently working on implementing a custom AJAX search by post title. My goal now is to search by tags instead. The code for the post title search can be found in functions.php and looks like this:

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('#grid').html( data );
    }
});

}
</script>

<?php
}

 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' => -1, 's' => 
 esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) :
    while( $the_query->have_posts() ): $the_query->the_post(); 

        if(get_field('type') == "box") {
            ?>
            <div class="grid-item grid-item--<?php echo get_field('type');?> <?php echo get_field('position');?>" data-tooltitle="Hood Baroque" data-tooltip="Design | 3D modeling | Drawings">
                <a class="linkpost" href="<?php echo get_post_permalink()?>"><img src="<?php the_field('picture');?>" alt=""></a>
                <a href="<?php echo get_post_permalink()?>" class="text">
                    <img src="<?php the_field('svg_picture');?>" alt="">
                </a>
            </div>
    <?php

        } else {
    ?>
    <div class="grid-item grid-item--<?php echo get_field('type');?> left" data-tooltitle="Hood Baroque" data-tooltip="Design | 3D modeling | Drawings">
        <a class="linkpost" href="<?php echo get_post_permalink()?>"><img src="<?php echo get_field('picture');?>" alt=""></a>
            <a href="<?php echo get_post_permalink()?>" class="text">
                <img src="<?php echo get_field('svg_picture');?>" alt="">
            </a>
    </div>

    <?php 
        }

     endwhile;
    wp_reset_postdata();  
endif;

die();
}

Any idea how to implement a search by tags ONLY?

Answer №1

Extracted from the WordPress codex:

Showcasing Posts With Multiple Tags

Illustrating how to display posts that contain "either" of the following tags:

$query = new WP_Query( array( 'tag' => 'bread,baking' ) );

Demonstrating how to exhibit posts that have "all" of these specific tags:

$query = new WP_Query( array( 'tag' => 'bread+baking+recipe' ) );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Output the chosen item quantity in the WooCommerce cart

Is there a way to showcase the quantity of added products in the cart on the single product page as a text image? Here is what I'm currently using in functions.php, but I need to include the quantity number within: add_action('woocommerce_before ...

Navigating to a particular div using a click event

I am trying to achieve a scrolling effect on my webpage by clicking a button that will target a specific div with the class "second". Currently, I have implemented this functionality using jQuery but I am curious about how to accomplish the same task using ...

Creating a Delicious Earth Progress Pie

I'm looking to incorporate a unique progress bar design on my website, similar to this one: The progress pie Can anyone guide me on how to create a progress pie with an image inside it that changes color as it moves? ...

Programmatically simulate a text cursor activation as if the user has physically clicked on the input

I have been attempting to input a value into a text field using JavaScript, similar to the Gmail email input tag. However, I encountered an issue with some fancy animations that are tied to certain events which I am unsure how to trigger, illustrated in th ...

Instructions on allowing the user to enter text for searching through an array of objects, and displaying a message if a match is found. Use only pure JavaScript

As a newcomer to JavaScript, I greatly appreciate the support from everyone on this platform. Thank you in advance for your help! I am currently working on building a basic music app as a learning project in JavaScript. The main goal is to understand how J ...

To modify the specified variables in data, I must deconstruct the object

Hello everyone, this is my debut post. I am seeking assistance with destructuring in order to update a variable that is defined within the "data" section. Below are the code snippets I have been working on using Vue. data: () => ({ id: '' ...

The error message received states: "materialize-css Uncaught TypeError: Vel is not defined as

My current setup involves webpack as the bundler/loader, and I've successfully loaded materialize css (js/css). However, when attempting to use the toast feature, an error is thrown: Uncaught TypeError: Vel is not a function The library is being inc ...

Accordion Box glitch detected in Firefox browser

I have been working on a JavaScript function that controls a slide up/down box. However, I've encountered some issues with Firefox as the box only opens and closes once before failing to work properly again. Upon further investigation, it seems that F ...

Displaying a message for PHP login validation when the password is entered correctly

I have implemented a login page on my website using PHP. I want to show error messages if the username does not exist, if the password is incorrect, or if either field is left empty when validating the form. Most of my validation code works fine except f ...

Variability in Swagger parameter declaration

Is it possible to specify input parameters in Swagger with multiple types? For example: Consider an API that addresses resources using the URL http://localhost/tasks/{taskId}. However, each task contains both an integer ID and a string UUID. I would like ...

Switching React components with const

Having some difficulties with the React Switch feature. Attempting to create a layout within another layout, and so far, everything seems to be functioning correctly. import React from "react"; import {Redirect, Route, Switch} from "react-router-dom"; imp ...

The scroll event is triggered only when scrolling upwards

I am encountering an issue with my scroll function. Currently, it only alerts when scrolling to the top instead of the bottom. How can I correct this so that it triggers the alert when reaching the bottom of the page? $(window).scroll(function() { if ...

Tips for utilizing the ternary operator in PHP:

One interesting observation I made while using the ternary operator in PHP is that 0, '0', and null are considered null This struck me as a bit odd because even though '0' is treated as a string, it still evaluates to null in a ternary ...

Why aren't variables showing up on the right when using writeFileSync in Node.js?

I'm attempting to insert a variable as ${Y} but instead of getting the actual data in Y, my output is showing (how can I write variable ${Y}). Does anyone have a solution for this? const fs = require('fs'); const Y = fs.readFileSync('./ ...

What is the best way to configure the loading state of my spinner?

When a user clicks to navigate to the articles page, I want to display a spinner while waiting for the articles data to be fetched and displayed. There is a slight delay after the click, hence the need for the spinner. I have a custom spinner component ca ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

Typescript versus ES5: A comparison of Node.js server-side applications written in different languages

Note: When I mention regular JavaScript, I am referring to the ES5 version of JS. As I lay down the groundwork for a new project, my chosen tech stack consists of Node.js for the back-end with Angular2 for the front-end/client-side, and Gulp as the build ...

Neither req.body nor req.file contain any data

Hey everyone, I'm new to coding and currently working on creating a basic markdown blog. However, I'm facing an issue where req.body doesn't contain my markdown field and req.file is undefined when trying to upload an article. I'm unsur ...

JavaScript Simplified Data Sorting after Reduction

I have extracted data from a JSON file and successfully condensed it to show the number of occurrences. Now, my next step is to arrange these occurrences in descending order, starting with the most frequent. To illustrate: var myData = [{ "datapo ...

Chrome is the only browser that will experience a failure in a CORS request if it includes

When attempting to make a simple CORS request to an external application server that uses a session key for authorization, I encountered some issues. $.ajax({ type: "GET", url: "https://192.168.1.72:8442/api/file/", headers: {"Authorization": ...