我使用WordPress Sage Starter主题(https://roots.io/sage/)。它使用名称空间来进行函数声明。使用函数作为用名称空间声明的另一个函数的回调
我在我的lib/extras.php文件中有一个函数(my_function_comments)来修改注释标记。这个文件有这个名字空间:namespace Roots \ Sage \ Extras; 现在我需要使用该函数作为回调的另一个文件模板/ comments.php了,因为这:
<?php wp_list_comments(array('style' => 'ol',
'short_ping' => true,
'avatar_size' => 60,
'type' => 'comment',
'callback' => 'my_function_comments',
)); ?>
当然,my_function_comments是不会在这个文件,所以我编写调用这样wp_list_comments:
<?php use Roots\Sage\Extras; ?>
<?php wp_list_comments(array('style' => 'ol',
'short_ping' => true,
'avatar_size' => 60,
'type' => 'comment',
'callback' => 'Extras\my_function_comments',
)); ?>
好吧,回调函数显然是错误的,但我不知道如何编写它来正确调用它。
也许有人可以帮助我弄清楚这一点。
谢谢!
PS。命名空间相关文档可在此找到(命名空间部分):https://roots.io/upping-php-requirements-in-your-wordpress-themes-and-plugins/。也许这将有助于回答我的问题。
函数与名称空间声明,只有类(及其方法)无关。如果你包含函数所在的文件,并且它在全局范围内,那么它是可访问的。但如果它是一种方法,那么你应该看到它的可访问性属性(如果是静态的,那么'Extras \ Class :: my_function_comments',否则,'Extras \ Class-> my_function_comments') –
在回调中使用完整的命名空间串)。当wordpress执行回调时,命名空间是必需的,而不是在声明它时。您可以使用'use'省略该行。 – WeSee
谢谢你们两位!我会尝试发布解决方案。谢谢! –