您可以将逻辑封装在类中:
class NameSwitch
{
private $state = false;
private $string;
public function __construct( $string )
{
$this->string = $string;
}
public function change_state()
{
$this->state = ! $this->state;
return $this->state;
}
public function replace( $output, $show = NULL )
{
if ( \'name\' !== $show )
return $output;
if ( ! $this->state )
return $output;
return $this->string;
}
}
然后在上创建该类的实例
template_redirect
要将其限制在前端,并像以前一样将方法分配为回调,请执行以下操作:
add_action( \'template_redirect\', function()
{
$switch = new NameSwitch(
"<span class=\'info-style\'>Info</span><span class=\'psi-style\'>Psi</span><span class=\'md-style\'>.md</span>"
);
add_action( \'wp_head\', [ $switch, \'change_state\' ], PHP_INT_MAX );
add_action( \'wp_footer\', [ $switch, \'change_state\' ], 0 );
add_filter( \'bloginfo\', [ $switch, \'replace\' ], 10, 2 );
});
但你真正应该做的是:
将呼叫替换为bloginfo()
使用自定义函数或do_action(\'custom_name\')
. 这样就不必运行过滤器,只需返回自定义值即可。