2017-02-14 60 views
0

我正在一個WordPress網站上工作。基本上,我發佈了下載鏈接(PDF),並希望阻止網絡爬蟲訪問此內容。這使我轉向了Google的reCAPTCHA。我是否可以單獨使用它,以便當用戶點擊/正確回答時,頁面上的鏈接將變爲活動狀態?我在編輯WordPress的頁面時遇到了麻煩。謝謝。reCAPTCHA成功後激活鏈接?

-Rudy。

回答

1

我知道您希望在驗證recaptcha後動態顯示鏈接。

您可以創建一個ajax,在驗證通過後獲取鏈接。 要做到這一點,我們將使用WordPress的Ajax請求,wp-ajax

首先,你註冊了ajax處理程序在服務器端

add_action('wp_ajax_get_hidden_pdf_link', 'search_hidden_pdf_link'); 

// add this line to handle requests of non logged in users 
add_action('wp_ajax_nopriv_get_hidden_pdf_link', 'search_hidden_pdf_link'); 


function search_hidden_pdf_link() { 
    // the response will be ajax response 
    header('Content-Type: application/json;charset=utf-8'); 

    if(recaptcha_fails()){ 
    // writing the failure response 
    echo json_encode(array('object' => 'error')); 
    wp_die(); 
    } 

    $secret_pdf_link = generate_pdf_link(); 

    // writing the succcess response 
    echo(json_encode(array('object' => 'success', 'link' => $secret_pdf_link))); 
    wp_die(); 
} 

,並在前端的要求,爲您營造一個ajax的形式,要求並顯示該鏈接。

<a href="#" id="hidden-pdf-link">PDF Link</a> 
    <form id="pdf-link-form" action="<?php echo admin_url('wp-ajax.php'); ?>"> 
     <!-- some input that tells the backend which pdf to fetch --> 
     <input type="hidden" name="public_pdf_id" value="<?php echo $pdf_id; ?>"> 
     <!-- the ajax request identifier, it is the suffix inside the action --> 
     <input type="hidden" name="action" value="get_hidden_pdf_link"> 
     <div class="g-recaptcha" data-sitekey="your_site_key"></div> 
    </form> 

    <script> 
     $(document).ready(function() { 
      $('#pdf-link-form').submit(function (event) { 
       event.preventDefault(); 
       form = $(this); 
       $.ajax({ 
        type: 'POST', 
        url: form.attr('action'), 
        data: form.serializeArray() 
       }).done(function (result) { 
        if(result.object == 'success'){ 
         $('#hidden-pdf-link').attr('href', result.link); 
         form.remove(); 
         alert('you can access the pdf') 
        } else { 
         alert('you are not allowed to access my pdf!!'); 
        } 
       }) 
      }); 
     }); 
    </script> 
+0

謝謝,@motie。我是WP的新手,但是第一塊代碼應該放在主題中的'functions.php'文件中? –

+0

另外,如果它將不同的reCAPTCHA應用於每個鏈接,這可能會很麻煩。 –

+0

@RudyM,將腳本添加到函數將工作。 對於recaptcha,您可以對所有鏈接使用相同的鏈接。你所要做的就是調整代碼片段,一次發送和顯示多個鏈接。 – motia