在wp中循环Add_action时需要帮助

时间:2012-09-01 作者:motekpc

我想知道正确的方法

$dynValue=5;//loop this many times
//start of my loop
for ($num=1; $num <= $dynValue; $num++){

//note the incremented number ($num) in the call back
add_action(\'add_meta_boxes\', \'mpc_meta_box_\'.$num.\');

//below is where im having the problem
// i am trying to increment this function name so i will not get the error that "function name has already been declared". i cannot add \'.$num.\' in the func name below cause its not valid php.
function mpc_meta_box_\'.$num.\'(){
//some content
}

}//end of my loop
我可以用eval()来实现这一点,但我知道不建议这样做

2 个回复
SO网友:Mathias

您可以尝试以下操作:

$dynValue=5;//loop this many times
//start of my loop
for ($num=1; $num <= $dynValue; $num++){
    add_action(\'add_meta_boxes\', create_function(\'\', \'//some content\'));
    // Write the php code as if it was to put it in an echo/print instruction.
    // More details: http://php.net/manual/en/function.create-function.php
}//end of my loop

SO网友:fuxia

始终使用与回调相同的函数。您可以在函数内部使用静态变量来跟踪调用它的频率:

for ($num=1; $num <= $dynValue; $num++) 
{
    add_action( \'add_meta_boxes\', \'mpc_meta_box\' );
}

function mpc_meta_box()
{
    static $counter = 1;
    echo $counter;
    counter++;
}
但我认为你需要找到一个更好的架构。

结束

相关推荐

Redirect Loops Problems

我不知道到底发生了什么事。昨天,它工作得很好。我回忆起今天早上我所做的让我陷入这种困境的事情。昨天,我刚刚在PhpMyAdmin编辑帖子。好吧,不管怎样,我禁用了所有插件,并找出什么不起作用。这是插件自定义永久链接。My problem is that I have about hundred videos in youtube, and each video is given with Custom Permalink set. I want to keep the Custom Permalink P