<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rehmatullah Khan</title>
    <description>The latest articles on DEV Community by Rehmatullah Khan (@rehmatullahbaltikhan).</description>
    <link>https://dev.to/rehmatullahbaltikhan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2470056%2Fb4fb9471-c559-4cdc-8f4b-b859b1a6dd7c.jpg</url>
      <title>DEV Community: Rehmatullah Khan</title>
      <link>https://dev.to/rehmatullahbaltikhan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rehmatullahbaltikhan"/>
    <language>en</language>
    <item>
      <title>How to Fetch and Integrate Multiple Location API Data into Google Maps in WordPress Without Plugins</title>
      <dc:creator>Rehmatullah Khan</dc:creator>
      <pubDate>Thu, 12 Dec 2024 12:41:34 +0000</pubDate>
      <link>https://dev.to/rehmatullahbaltikhan/how-to-fetch-and-integrate-multiple-location-api-data-into-google-maps-in-wordpress-without-plugins-1g74</link>
      <guid>https://dev.to/rehmatullahbaltikhan/how-to-fetch-and-integrate-multiple-location-api-data-into-google-maps-in-wordpress-without-plugins-1g74</guid>
      <description>&lt;p&gt;&lt;strong&gt;Step-1:&lt;/strong&gt;&lt;br&gt;
add your google map api in your header.php file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script async defer src="https://maps.googleapis.com/maps/api/js?key=Your_API_Key&amp;amp;callback=initMap"&amp;gt;&amp;lt;/script&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step-2:&lt;/strong&gt;&lt;br&gt;
Create Function in Functions.php file for fetch Api adress list and pass to js function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// Fetch Api Data And Pass data to JavaScript Functions
function enqueue_google_maps_scripts() {

    $url = 'https://example.com/public-api/resources/locations/v2.0';
    $response = wp_remote_get($url, array(
        'headers' =&amp;gt; array(
            'Accept' =&amp;gt; 'application/json',
            'Authorization' =&amp;gt; 'Bearer Your API Token',
        ),
    ));

    if (is_wp_error($response)) {
        error_log('Error fetching data: ' . $response-&amp;gt;get_error_message());
        return [];
    }

    $data = wp_remote_retrieve_body($response);
    $locations = json_decode($data, true); // Decode JSON into an array

    // Enqueue Google Maps API
    wp_enqueue_script(
        'google-maps-api',
        'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY',
        [],
        null,
        true
    );

    // Enqueue custom map script
    wp_enqueue_script(
        'custom-google-map',
        get_template_directory_uri() . '/js/custom-google-map.js',
        ['google-maps-api'],
        null,
        true
    );

    // Fetch and pass location data to JavaScript
//     $locations = get_citicharge_locations();

//  echo '&amp;lt;pre&amp;gt;';
//  print_r($locations);
//  echo '&amp;lt;/pre&amp;gt;';

    wp_localize_script('custom-google-map', 'citichargeData', [
        'locations' =&amp;gt; $locations,
    ]);
}
add_action('wp_enqueue_scripts', 'enqueue_google_maps_scripts');


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step-3:&lt;/strong&gt;&lt;br&gt;
create js file like /js/custom-google-map.js and add code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function initMap() {
//  console.log("Initializing map...");
//     console.log("Locations data:", citichargeData.locations);
    var map = new google.maps.Map(document.getElementById("map"), {
        zoom: 5,
        center: { lat: 51.509865, lng: -0.118092 } // Example: Centered on London
    });

    var bounds = new google.maps.LatLngBounds();
    var locations = citichargeData.locations;
//     var locations = [
//         {
//             geoposition: { latitude: 42.6710963, longitude: 23.3520653 },
//             name: [{ translation: "Ampeco Office" }],
//             address: [{ translation: "Sofia, Bulgaria" }]
//         },
//         {
//             geoposition: { latitude: 51.5194133, longitude: -0.1269566 },
//             name: [{ translation: "British Museum" }],
//             address: [{ translation: "London, UK" }]
//         }
//         // Add other locations
//     ];
    locations.data.forEach(function (location) {
//      console.log("Loop Data",location);
        var position = {
            lat: location.geoposition.latitude,
            lng: location.geoposition.longitude
        };
//      console.log("position",position);

        var marker = new google.maps.Marker({
            position: position,
            map: map,
            title: location.name[0].translation
        });

        var infoWindow = new google.maps.InfoWindow({
            content: ` &amp;lt;h4&amp;gt;${location.name[0].translation}&amp;lt;/h4&amp;gt;
                        &amp;lt;p&amp;gt;${location.address[0].translation}&amp;lt;/p&amp;gt;
                        &amp;lt;button onclick="viewOnGoogleMaps(${location.geoposition.latitude}, ${location.geoposition.longitude})"&amp;gt;View on Google Maps&amp;lt;/button&amp;gt;`
        });

        marker.addListener("click", function () {
            infoWindow.open(map, marker);
        });

        bounds.extend(position);
    });

    map.fitBounds(bounds);
}

function viewOnGoogleMaps(lat, lng) {
    var googleMapsUrl = `https://www.google.com/maps?q=${lat},${lng}`;
    window.open(googleMapsUrl, '_blank'); // Open Google Maps in a new tab
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step-4:&lt;/strong&gt;&lt;br&gt;
create shortcod for display Google Map:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function display_google_map_shortcode() {
    return '&amp;lt;div id="map" style="width: 100%; height: 500px;"&amp;gt;&amp;lt;/div&amp;gt;';
}
add_shortcode('google_map', 'display_google_map_shortcode');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>wordpress</category>
      <category>api</category>
      <category>map</category>
    </item>
    <item>
      <title>How to Create a WordPress Custom Login Popup Modal without any plugin.</title>
      <dc:creator>Rehmatullah Khan</dc:creator>
      <pubDate>Sat, 07 Dec 2024 09:51:52 +0000</pubDate>
      <link>https://dev.to/rehmatullahbaltikhan/how-to-create-a-wordpress-login-popup-modal-without-any-plugin-252e</link>
      <guid>https://dev.to/rehmatullahbaltikhan/how-to-create-a-wordpress-login-popup-modal-without-any-plugin-252e</guid>
      <description>&lt;p&gt;&lt;strong&gt;sign in Step-1:&lt;/strong&gt;&lt;br&gt;
Create Cusom login form shortcode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// custom sign in popup form shortcod
function custom_login_form() {

    // Display the login form
    ob_start();

    ?&amp;gt;
    &amp;lt;form method="post" class="formValidationQuery login-form"&amp;gt;
        &amp;lt;div class="form-group"&amp;gt;
            &amp;lt;label for=""&amp;gt;*User Name&amp;lt;/label&amp;gt;
            &amp;lt;input type="email" id="youremail" name="useremail" placeholder="Email Address" required /&amp;gt;
            &amp;lt;span class="formError" id="youremailError"&amp;gt;&amp;lt;/span&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div class="form-group"&amp;gt;
        &amp;lt;label for=""&amp;gt;*Password&amp;lt;/label&amp;gt;
            &amp;lt;input type="password" name="password" id="loginPassword" placeholder="Password" required /&amp;gt;
            &amp;lt;span class="formError" id="loginPasswordError"&amp;gt;&amp;lt;/span&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div class="d-flexinline"&amp;gt;                    
            &amp;lt;input type="checkbox" id="checkbox" name="checkbox" /&amp;gt;
            &amp;lt;span class="checkboxtext" id="logincheckboxtex"&amp;gt;Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
                Lorem Ipsum has been the industry's standard dummy text ever since the 1500s&amp;lt;/span&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;button type="submit" name="login" class="btn" id="login-btn"&amp;gt;
            &amp;lt;span&amp;gt;Sign In&amp;lt;/span&amp;gt;
            &amp;lt;span class="spinner" style="display: none;"&amp;gt;&amp;lt;/span&amp;gt;
        &amp;lt;/button&amp;gt;                   

    &amp;lt;/form&amp;gt;
    &amp;lt;?php
}
add_shortcode('custom_login', 'custom_login_form');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;sign in Step-2:&lt;/strong&gt;&lt;br&gt;
Create login form handle function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// custom sign in poup form handle
function handle_custom_login() {
    if (isset($_POST['login'])) {
        $useremail = sanitize_user($_POST['useremail']);
        $password = sanitize_text_field($_POST['password']);
        $creds = array(
            'user_login'    =&amp;gt; $useremail,
            'user_password' =&amp;gt; $password,
            'remember'      =&amp;gt; isset($_POST['remember']),
        );

        $user = wp_signon($creds, false);

        if (is_wp_error($user)) {
            echo '&amp;lt;script&amp;gt;alert("Login failed: ' . $user-&amp;gt;get_error_message() . '");&amp;lt;/script&amp;gt;';
        } else {
            wp_redirect(home_url());
            exit;
        }
    }
}
add_action('init', 'handle_custom_login');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;sign in Step-3:&lt;/strong&gt;&lt;br&gt;
add shortcod in your popup modal.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Custom Sign up&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;sign up Step-1:&lt;/strong&gt;&lt;br&gt;
Create function for Cusom Sign up form shortcode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// custom registration form

function custom_registration_form() {

    ?&amp;gt;
    &amp;lt;form method="post" class="formValidationQueryRegister login-form"&amp;gt;
        &amp;lt;div class="form-group"&amp;gt;
            &amp;lt;label for=""&amp;gt;*User Name&amp;lt;/label&amp;gt;
            &amp;lt;input type="text" id="yourname" name="username" placeholder="Username" required /&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div class="form-group"&amp;gt;
            &amp;lt;label for=""&amp;gt;*User Email&amp;lt;/label&amp;gt;
            &amp;lt;input type="email" id="youremail" name="email" placeholder="Email" required /&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div class="form-group"&amp;gt;
        &amp;lt;label for=""&amp;gt;*Password&amp;lt;/label&amp;gt;
            &amp;lt;input type="password" name="password" id="loginPassword" placeholder="Password" required /&amp;gt;
            &amp;lt;span class="formError" id="loginPasswordError"&amp;gt;&amp;lt;/span&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div class="d-flexinline"&amp;gt;                    
            &amp;lt;input type="checkbox" id="checkbox" name="checkbox" /&amp;gt;
            &amp;lt;span class="checkboxtext" id="logincheckboxtex"&amp;gt;Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
                Lorem Ipsum has been the industry's standard dummy text ever since the 1500s&amp;lt;/span&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;button type="submit" name="register" class="btn" id="login-btn"&amp;gt;
            &amp;lt;span&amp;gt;Sign In&amp;lt;/span&amp;gt;
            &amp;lt;span class="spinner" style="display: none;"&amp;gt;&amp;lt;/span&amp;gt;
        &amp;lt;/button&amp;gt;                   

    &amp;lt;/form&amp;gt;
    &amp;lt;?php
}
add_shortcode('custom_registration', 'custom_registration_form');


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;sign up Step-2:&lt;/strong&gt;&lt;br&gt;
Create function for handle Sign up form request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// custom sign up form handle
function handle_custom_signup() {
    if (isset($_POST['register'])) {
        $username = sanitize_user($_POST['username']);
        $email = sanitize_email($_POST['email']);
        $password = sanitize_text_field($_POST['password']);

        // Check if the username and email already exist
        if (username_exists($username)) {
            echo '&amp;lt;script&amp;gt;alert("Username already exists.");&amp;lt;/script&amp;gt;';
            return;
        }
        if (email_exists($email)) {
            echo '&amp;lt;script&amp;gt;alert("Email is already registered.");&amp;lt;/script&amp;gt;';
            return;
        }

        // Create a new user
        $user_id = wp_create_user($username, $password, $email);

        if (is_wp_error($user_id)) {
            echo '&amp;lt;script&amp;gt;alert("Error: ' . $user_id-&amp;gt;get_error_message() . '");&amp;lt;/script&amp;gt;';
        } else {
            echo '&amp;lt;script&amp;gt;alert("Registration successful! You can now log in.");&amp;lt;/script&amp;gt;';
        }
    }
}
add_action('init', 'handle_custom_signup');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>webdev</category>
      <category>wordpress</category>
      <category>php</category>
    </item>
    <item>
      <title>How to Filter multiple Posts in WordPress by tag Using AJAX, without using any plugin</title>
      <dc:creator>Rehmatullah Khan</dc:creator>
      <pubDate>Thu, 05 Dec 2024 07:06:57 +0000</pubDate>
      <link>https://dev.to/rehmatullahbaltikhan/how-to-filter-multiple-wordpress-posts-by-tag-using-ajax-without-using-any-plugin-29b4</link>
      <guid>https://dev.to/rehmatullahbaltikhan/how-to-filter-multiple-wordpress-posts-by-tag-using-ajax-without-using-any-plugin-29b4</guid>
      <description>&lt;p&gt;&lt;strong&gt;Step-1:&lt;/strong&gt;&lt;br&gt;
Html Checkbox Like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class="list"&amp;gt;
&amp;lt;label for="arts" class="font"&amp;gt;
   &amp;lt;input type="checkbox" class="subject-filter" name="subject[]" data - 
    taxonomy="worksheet-subject" value="arts" id="arts" /&amp;gt;Arts
&amp;lt;/label&amp;gt;
&amp;lt;label for="biology" class="font"
                  &amp;gt;&amp;lt;input type="checkbox" class="subject-filter" name="subject[]" data-taxonomy="worksheet-subject" value="biology" id="biology" /&amp;gt;Biology&amp;lt;/label&amp;gt;
&amp;lt;label for="chemistry" class="font"&amp;gt;
&amp;lt;input type="checkbox" class="subject-filter" name="subject[]" data-taxonomy="worksheet-subject" value="chemistry" id="chemistry"/&amp;gt;
Chemistry&amp;lt;/label&amp;gt;
&amp;lt;label for="bio" class="font"&amp;gt;
&amp;lt;input type="checkbox" class="subject-filter" name="subject[]" data-taxonomy="worksheet-subject" value="grammar" id="grammar" /&amp;gt;
Grammar&amp;lt;/label&amp;gt;
&amp;lt;label for="lang" class="font"&amp;gt;
&amp;lt;input type="checkbox" class="subject-filter" name="subject[]" data-taxonomy="worksheet-subject" value="language" id="language" /&amp;gt;
Language&amp;lt;/label&amp;gt;
&amp;lt;label for="arts" class="font"&amp;gt;
&amp;lt;input type="checkbox" class="subject-filter" name="subject[]" data-taxonomy="worksheet-subject" value="maths" id="maths" /&amp;gt;Maths&amp;lt;/label&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;display all tabs or subjects container:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- Container to display worksheets --&amp;gt;
&amp;lt;div class="worksheet-container"&amp;gt;
&amp;lt;p&amp;gt;Select grades to view worksheets.&amp;lt;/p&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step-2:&lt;/strong&gt;&lt;br&gt;
create js file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;jQuery(document).ready(function ($) {
    // Fetch Subjects on any checkbox change
    $('.subject-filter').on('change', function () {
        // Gather all selected grades
        var taxonomy = $(this).data('taxonomy'); // Taxonomy name
        var terms = []; // Array to hold selected terms
        $('.subject-filter:checked').each(function () {
            terms.push($(this).val());
        });

        // Fetch Subjects for selected grades
        fetchSubjects(taxonomy, terms);
    });

    // Function to fetch Subjects
    function fetchSubjects(taxonomy = '', terms = []) {
        $.ajax({
            url: ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'fetch_subjects',
                nonce: ajax_object.nonce,
                taxonomy: taxonomy,
                terms: terms, // Send array of selected terms
            },
            beforeSend: function () {
                $('.worksheet-container').html('&amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;');
            },
            success: function (response) {
                if (response.success) {
                    $('.worksheet-container').html(response.data.html);
                } else {
                    $('.worksheet-container').html('&amp;lt;p&amp;gt;' + response.data.message + '&amp;lt;/p&amp;gt;');
                }
            },
            error: function () {
                $('.worksheet-container').html('&amp;lt;p&amp;gt;An error occurred. Please try again.&amp;lt;/p&amp;gt;');
            },
        });
    }
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step-3:&lt;/strong&gt;&lt;br&gt;
Create Functions in functions.php:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Register AJAX action for logged-in users (you can add for non-logged-in users too)
add_action('wp_ajax_fetch_subjects', 'fetch_subjects');
add_action('wp_ajax_nopriv_fetch_subjects', 'fetch_subjects');
function fetch_subjects() {
    // Verify nonce for security
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ajax_nonce')) {
        wp_send_json_error(array('message' =&amp;gt; 'Nonce verification failed.'));
        wp_die();
    }

    // Get taxonomy and terms from the AJAX request
    $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : '';
    $terms = isset($_POST['terms']) ? array_map('sanitize_text_field', $_POST['terms']) : array();

    // Default query arguments
    $args = array(
        'post_type'      =&amp;gt; 'worksheet',
        'posts_per_page' =&amp;gt; -1, // Fetch all posts
    );

    // If terms are selected, modify the query
    if (!empty($taxonomy) &amp;amp;&amp;amp; !empty($terms)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' =&amp;gt; $taxonomy,
                'field'    =&amp;gt; 'slug',
                'terms'    =&amp;gt; $terms, // Pass the array of selected terms
                'operator' =&amp;gt; 'IN',   // Match any of the selected terms
            ),
        );
    }

    // Run WP_Query to fetch posts
    $query = new WP_Query($args);

    // Check if any posts were found
    if ($query-&amp;gt;have_posts()) {
        $html = '';
        while ($query-&amp;gt;have_posts()) {
            $query-&amp;gt;the_post();
            // Output the post HTML
            $html .= '&amp;lt;div class="card"&amp;gt;';
            $html .= '&amp;lt;div class="card-img"&amp;gt;';
            // Add the post thumbnail
            if (has_post_thumbnail()) {
                $thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'medium'); // Get the thumbnail URL
                $html .= '&amp;lt;img src="' . esc_url($thumbnail_url) . '" class="worksheets-card-img" alt="' . esc_attr(get_the_title()) . '" /&amp;gt;';
            } else {
                $html .= '&amp;lt;img src="placeholder-image.jpg" class="worksheets-card-img" alt="Placeholder" /&amp;gt;'; // Fallback for no thumbnail
            }
            $html .= '&amp;lt;div class="grade"&amp;gt;';
            // Add the first category name or fallback
            $terms = get_the_terms(get_the_ID(), 'worksheet-grad');
            if ($terms &amp;amp;&amp;amp; !is_wp_error($terms)) {
                foreach ($terms as $term) {
                    $html .= esc_html($term-&amp;gt;name); // Display the first term name
                    break;
                }
            } else {
                $html .= 'No Grade Available'; // Fallback message
            } 

            $html .= '&amp;lt;/div&amp;gt;';
            $html .= '&amp;lt;div class="age"&amp;gt; For Age 1-12&amp;lt;/div&amp;gt;';            
            $html .= '&amp;lt;/div&amp;gt;';            
            $html .= '&amp;lt;div class="card-content"&amp;gt;';
            $html .= '&amp;lt;h2&amp;gt;&amp;lt;a href="' . esc_url(get_permalink()) . '"&amp;gt;' . get_the_title() . '&amp;lt;/a&amp;gt;&amp;lt;/h2&amp;gt;';
            $html .= '&amp;lt;p&amp;gt;'. get_the_excerpt() .'&amp;lt;/p&amp;gt;';
            $html .= '&amp;lt;/div&amp;gt;';
            $html .= '&amp;lt;/div&amp;gt;';
        }
        wp_send_json_success(array('html' =&amp;gt; $html));
    } else {
        wp_send_json_error(array('message' =&amp;gt; 'No worksheets found.'));
    }

    wp_die(); // Always terminate the request properly
}
`
**Step-4:**
enqueue scripts file using functions.php:
`
function enqueue_custom_scripts() {
    wp_enqueue_script('custom-ajax', get_template_directory_uri() . '/js/custom-ajax.js', array('jquery'), null, true);

    // Localize script to pass ajax_url and nonce to JS
    wp_localize_script('custom-ajax', 'ajax_object', array(
        'ajax_url' =&amp;gt; admin_url('admin-ajax.php'),
        'nonce'    =&amp;gt; wp_create_nonce('ajax_nonce'),
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>wordpress</category>
      <category>acf</category>
      <category>php</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to Filter WordPress Posts by Category Using AJAX, without using any plugin</title>
      <dc:creator>Rehmatullah Khan</dc:creator>
      <pubDate>Wed, 27 Nov 2024 15:23:07 +0000</pubDate>
      <link>https://dev.to/rehmatullahbaltikhan/dynamic-ajax-post-filtering-by-taxonomy-using-radio-buttons-and-checkboxes-in-wordpress-2cpe</link>
      <guid>https://dev.to/rehmatullahbaltikhan/dynamic-ajax-post-filtering-by-taxonomy-using-radio-buttons-and-checkboxes-in-wordpress-2cpe</guid>
      <description>&lt;p&gt;Learn how to implement dynamic AJAX-based post filtering in WordPress. Fetch and display posts by taxonomy using radio buttons and checkboxes for seamless user interaction and improved functionality.&lt;br&gt;
First, we cover the functionality of the radio button filter.&lt;br&gt;
&lt;strong&gt;Step-1:&lt;/strong&gt;&lt;br&gt;
create js file and add this code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;jQuery(document).ready(function ($) {
    // Fetch all worksheets by default when the page loads
    fetchWorksheets();

    // Trigger AJAX request when a grade filter is selected
    $('.grade-filter').on('change', function () {
        var taxonomy = $(this).data('taxonomy'); // e.g., 'worksheet-grad'
        var term = $(this).val(); // Selected term slug
        fetchWorksheets(taxonomy, term);
    });

    // Function to fetch worksheets
    function fetchWorksheets(taxonomy = '', term = '') {
        $.ajax({
            url: ajax_object.ajax_url,
            type: 'POST',
            data: {
                action: 'fetch_worksheets',
                nonce: ajax_object.nonce,
                taxonomy: taxonomy,
                term: term,
            },
            beforeSend: function () {
                $('.worksheet-container').html('&amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;');
            },
            success: function (response) {
                if (response.success) {
                    $('.worksheet-container').html(response.data.html);
                } else {
                    $('.worksheet-container').html('&amp;lt;p&amp;gt;' + response.data.message + '&amp;lt;/p&amp;gt;');
                }
            },
            error: function () {
                $('.worksheet-container').html('&amp;lt;p&amp;gt;An error occurred. Please try again.&amp;lt;/p&amp;gt;');
            },
        });
    }




});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step-2:&lt;/strong&gt;&lt;br&gt;
add this code in functions.php file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// Register AJAX action for logged-in users (you can add for non-logged-in users too)
add_action('wp_ajax_fetch_worksheets', 'fetch_worksheets');
add_action('wp_ajax_nopriv_fetch_worksheets', 'fetch_worksheets');

function fetch_worksheets() {
    // Verify nonce for security
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ajax_nonce')) {
        wp_send_json_error(array('message' =&amp;gt; 'Nonce verification failed.'));
        wp_die();
    }

    // Get taxonomy and term from the AJAX request
    $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : '';
    $term = isset($_POST['term']) ? sanitize_text_field($_POST['term']) : '';

    // Default query arguments
    $args = array(
        'post_type'      =&amp;gt; 'worksheet',
        'posts_per_page' =&amp;gt; -1, // Fetch all posts
    );

    // If a specific term is selected, modify the query
    if (!empty($taxonomy) &amp;amp;&amp;amp; !empty($term)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' =&amp;gt; $taxonomy,
                'field'    =&amp;gt; 'slug',
                'terms'    =&amp;gt; $term, // Fetch posts of the selected term
            ),
        );
    }

    // Run WP_Query to fetch posts
    $query = new WP_Query($args);

    // Check if any posts were found
    if ($query-&amp;gt;have_posts()) {
        $html = '';
        while ($query-&amp;gt;have_posts()) {
            $query-&amp;gt;the_post();
            // Output the post HTML
            $html .= '&amp;lt;div class="card"&amp;gt;';
            $html .= '&amp;lt;h3&amp;gt;' . get_the_title() . '&amp;lt;/h3&amp;gt;';
            $html .= '&amp;lt;div class="worksheet-excerpt"&amp;gt;' . get_the_excerpt() . '&amp;lt;/div&amp;gt;';
            $html .= '&amp;lt;/div&amp;gt;';
        }
        wp_send_json_success(array('html' =&amp;gt; $html));
    } else {
        wp_send_json_error(array('message' =&amp;gt; 'No worksheets found.'));
    }

    wp_die(); // Always terminate the request properly
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step-3:&lt;/strong&gt;&lt;br&gt;
add this code in functions.php for enque custom js file in wp.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

function enqueue_custom_scripts() {
    wp_enqueue_script('custom-ajax', get_template_directory_uri() . '/js/custom-ajax.js', array('jquery'), null, true);

    // Localize script to pass ajax_url and nonce to JS
    wp_localize_script('custom-ajax', 'ajax_object', array(
        'ajax_url' =&amp;gt; admin_url('admin-ajax.php'),
        'nonce'    =&amp;gt; wp_create_nonce('ajax_nonce'),
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step-4:&lt;/strong&gt;&lt;br&gt;
The html code structure add this on your template file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; &amp;lt;div class="grade"&amp;gt;
            &amp;lt;h2 class="filter-heading"&amp;gt;GRADE&amp;lt;/h2&amp;gt;
            &amp;lt;ul&amp;gt;
                &amp;lt;li&amp;gt;
                &amp;lt;input type="radio" id="1st" name="radio" class="grade-filter" data-taxonomy="worksheet-grad" value="1st-grade" /&amp;gt;
                &amp;lt;label for="1st" class="font"&amp;gt;1st Grade&amp;lt;/label&amp;gt;
                &amp;lt;/li&amp;gt;
                &amp;lt;li&amp;gt;
                &amp;lt;input type="radio" id="2nd" name="radio" class="grade-filter" data-taxonomy="worksheet-grad" value="2nd-grade" /&amp;gt;
                &amp;lt;label for="2nd" class="font"&amp;gt;2nd Grade&amp;lt;/label&amp;gt;
                &amp;lt;/li&amp;gt;
            &amp;lt;/ul&amp;gt;
            &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: please the css class on radio button change according your css class and data-taxonomy="worksheet-grad"  alsoe. second important point is the value="2nd-grade"  is change to your category slug.&lt;/p&gt;

</description>
      <category>wordpress</category>
      <category>acf</category>
    </item>
  </channel>
</rss>
