簡體   English   中英

Wordpress 簡碼條件加載

[英]Wordpress shortcode conditional loading

我正在使用一個包含簡碼的 WordPress 插件。 由於外部 API 調用,這個短代碼很慢(執行 4 秒),我在這里需要它們,因為它們會因用戶 ID 而異,正在觀看頁面。

實際上,我正處於插件的開發/測試階段。 我正在嘗試實現一個回退行為,如果達到特定時間,它將跳過長 API 調用,然后使用本地邏輯。

我想知道,是否可以停止執行或有條件地呈現簡碼? 使用 While 循環不是解決方案,因為它至少會循環一次。

另外,我嘗試使用 set_time_limit(); PHP 內置function,但在WP 環境中似乎不起作用。

此外,如果可能的話,我試圖在沒有 AJAX 的情況下實現這一目標。 如果沒有,我當然也想要一些指導方針,如果你能幫助我的話。

如果您認為我需要其他解決方案,例如不使用短代碼,請告訴我。 延遲加載也可能是此 線程中的解決方案:

我想要實現的是擁有一個異步短代碼,可能帶有加載程序,看起來像現代 JS Web 應用程序。

為了監控我的短代碼的執行時間,我將其插入到我的 function 中:

<?php
function my_function() {
  $start = microtime(true);
  // function code here
  $time_taken = microtime(true) - $start;
  wp_die( $time_taken ); // in seconds
}

從這個來源謝謝你,任何線索都會對我有用。

更新

使用評論給出的線索,Ajax 是通往 go 的途徑。使用 wordpress register_script 和 localize_script 我讓它工作了。

由於我調用了 Api,數據大部分時間都會發生變化,但我發現我的 js 文件正在緩存該行為,並且在沒有硬刷新的情況下不會更新值。

如何防止瀏覽器或 Wordpress 對此進行緩存?

謝謝

如果時間是你最重要的因素,我會創建一個時間受限的循環:

$endafter=time()+4;
$completed=false;

while(time()!=$endafter){
    echo ".";
    //Do something
    $completed=true; //Only gets reached if code before it completes successfully
    break; //will break off the while loop so your API call only runs once
}
if($completed){
    //use the API call data
}else{
    //use some other data
}

至於避免不必要的 API 調用,您可以考慮緩存它們,並且僅在需要新數據時才進行 API 調用,比如在一段時間后,或者如果值發生變化。 I am uncertain the best way to implement this with the WordPress database object, but I've done it with customizations using straight PHP to compare the timestamp, and if it's expired, update it from the API and update the old timestamp with the current one .

讓我知道這是否有效!

使用 Ajax 是解決我的問題的最佳方法,如這篇文章中所示: https://stackoverflow.com/a/13614297/18036486

此外,為了防止觸發 ajax 處理程序的 javascript 被緩存,必須通過wp_register_script() https://developer.wordpress.org/reference/functions/wp_register_script/添加一個隨機版本號,例如使用時間().

<?php
wp_register_script(
    'myscript',
    MAIN_PLUGIN_DIR .'/scripts.js',
    false,
    time(), //random version number
    true);
wp_enqueue_script('myscript');
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM