搜尋
首頁後端開發php教程如何使用 AJAX 在 WordPress 中按標籤過濾多個帖子,而不使用任何插件

How to Filter multiple Posts in WordPress by tag Using AJAX, without using any plugin

第 1 步:
Html 複選框如下圖所示:

<div>



<p>display all tabs or subjects container:<br>
</p>

<pre class="brush:php;toolbar:false"><!-- Container to display worksheets -->
<div>



<p><strong>Step-2:</strong><br>
create js file:<br>
</p>

<pre class="brush:php;toolbar:false">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('<p>Loading...</p>');
            },
            success: function (response) {
                if (response.success) {
                    $('.worksheet-container').html(response.data.html);
                } else {
                    $('.worksheet-container').html('<p>' + response.data.message + '</p>');
                }
            },
            error: function () {
                $('.worksheet-container').html('<p>An error occurred. Please try again.</p>');
            },
        });
    }
});

第 3 步:
在functions.php中建立函數:

// 為登入使用者註冊AJAX操作(您也可以為非登入使用者新增)
add_action('wp_ajax_fetch_subjects', 'fetch_subjects');
add_action('wp_ajax_nopriv_fetch_subjects', 'fetch_subjects');
函數 fetch_subjects() {
    // 驗證隨機數以確保安全
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ajax_nonce')) {
        wp_send_json_error(array('message' => '隨機數驗證失敗。'));
        wp_die();
    }

    // 從 AJAX 請求中取得分類和術語
    $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['分類']) : '';
    $terms = isset($_POST['terms']) ? array_map('sanitize_text_field', $_POST['terms']) : array();

    // 預設查詢參數
    $args = 數組(
        'post_type'=>; '工作表',
        'posts_per_page' =>; -1, // 取得所有帖子
    );

    // 如果選擇了條件,則修改查詢
    if (!empty($taxonomy) && !empty($terms)) {
        $args['tax_query'] = 數組(
            大批(
                '分類法' => $分類法,
                '字段' => '蛞蝓',
                '條款' => $terms, // 傳遞所選術語的陣列
                '操作員' => 'IN', // 符合任何選定的術語
            ),
        );
    }

    // 執行 WP_Query 來取得帖子
    $query = new WP_Query($args);

    // 檢查是否發現任何帖子
    if ($query->have_posts()) {
        $html = '';
        while ($query->have_posts()) {
            $query->the_post();
            // 輸出貼文 HTML
            $html .= '<div>




          </div>

            
        

以上是如何使用 AJAX 在 WordPress 中按標籤過濾多個帖子,而不使用任何插件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
PHP如何識別用戶的會話?PHP如何識別用戶的會話?May 01, 2025 am 12:23 AM

phpIdentifiesauser'ssessionSessionSessionCookiesAndSessionId.1)whiwsession_start()被稱為,phpgeneratesainiquesesesessionIdStoredInacookInAcookInAcienamedInAcienamedphpsessIdontheuser'sbrowser'sbrowser.2)thisIdallowSphptpptpptpptpptpptpptpptoretoreteretrieetrieetrieetrieetrieetrieetreetrieetrieetrieetrieetremthafromtheserver。

確保PHP會議的一些最佳實踐是什麼?確保PHP會議的一些最佳實踐是什麼?May 01, 2025 am 12:22 AM

PHP會話的安全可以通過以下措施實現:1.使用session_regenerate_id()在用戶登錄或重要操作時重新生成會話ID。 2.通過HTTPS協議加密傳輸會話ID。 3.使用session_save_path()指定安全目錄存儲會話數據,並正確設置權限。

PHP會話文件默認存儲在哪裡?PHP會話文件默認存儲在哪裡?May 01, 2025 am 12:15 AM

phpsessionFilesArestoredIntheDirectorySpecifiedBysession.save_path,通常是/tmponunix-likesystemsorc:\ windows \ windows \ temponwindows.tocustomizethis:tocustomizEthis:1)useession_save_save_save_path_path()

您如何從PHP會話中檢索數據?您如何從PHP會話中檢索數據?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

您如何使用會議來實施購物車?您如何使用會議來實施購物車?May 01, 2025 am 12:10 AM

利用會話構建高效購物車系統的步驟包括:1)理解會話的定義與作用,會話是服務器端的存儲機制,用於跨請求維護用戶狀態;2)實現基本的會話管理,如添加商品到購物車;3)擴展到高級用法,支持商品數量管理和刪除;4)優化性能和安全性,通過持久化會話數據和使用安全的會話標識符。

您如何在PHP中創建和使用接口?您如何在PHP中創建和使用接口?Apr 30, 2025 pm 03:40 PM

本文解釋瞭如何創建,實施和使用PHP中的接口,重點關注其對代碼組織和可維護性的好處。

crypt()和password_hash()有什麼區別?crypt()和password_hash()有什麼區別?Apr 30, 2025 pm 03:39 PM

本文討論了PHP中的crypt()和password_hash()的差異,以進行密碼哈希,重點介紹其實施,安全性和對現代Web應用程序的適用性。

如何防止PHP中的跨站點腳本(XSS)?如何防止PHP中的跨站點腳本(XSS)?Apr 30, 2025 pm 03:38 PM

文章討論了通過輸入驗證,輸出編碼以及使用OWASP ESAPI和HTML淨化器之類的工具來防止PHP中的跨站點腳本(XSS)。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具