如何防止简码多次执行

问题描述

似乎在wordpress添加首页的短代码将执行多次,这可能是预期的行为。例如,在首页添加一个名为[myshortcode]的简码,并在functions.PHP中这样定义它:

function myshortcode()
{ 
     ob_start();

     // This is what really needs to be run only once
     update_my_database();

     return ob_get_clean();
}
add_shortcode('myshortcode','myshortcode');

wordpress似乎多次执行此操作。可以预防吗?还是有另一种方法可以在WP首页上一次只执行一次功能而无需使用简码?

我尝试了多种检查,包括in_the_loop()is_singular(),但似乎都没有。还尝试过在remove_shortcode('myshortcode');函数添加myshortcode,以为可能阻止后续执行,但是这也不起作用:尝试为https://stackoverflow.com/a/3695685/8552218添加静态变量,但不起作用。>

这是所有这些方法的外观,但这仍然行不通。有什么想法吗?

function myshortcode()
{ 
     ob_start();

     if (!is_singular()) return ob_get_clean;
     if (!in_the_loop()) return ob_get_clean;
     if (!is_main_query()) return ob_get_clean;

     static $runonce=false;
     if (!$runonce)
     { 
          $runonce=true;
          return;
     }

     // This is what really needs to be run only once
     update_my_database();
     
     remove_shortcode('myshortcode');

     return ob_get_clean();
}
add_shortcode('myshortcode','myshortcode');


function update_my_database()
{
     error_log("Executing...",1,$myemail);
} 

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)