Wordpress 如何从WP模板中的插件调用函数?
我已经创建了一个日历插件,现在我想在我的一个模板中显示一个事件列表。 我现在使用的代码是:Wordpress 如何从WP模板中的插件调用函数?,wordpress,Wordpress,我已经创建了一个日历插件,现在我想在我的一个模板中显示一个事件列表。 我现在使用的代码是: include_once(WP_CAL_PLUGIN_DIR.'eventcal.class.php'); $calendar = new EventCalendar(); $events = $calendar->getMultipleEvents('5'); (...) <table> <?php foreach($events as $event) : ?>
include_once(WP_CAL_PLUGIN_DIR.'eventcal.class.php');
$calendar = new EventCalendar();
$events = $calendar->getMultipleEvents('5');
(...)
<table>
<?php foreach($events as $event) : ?>
<tr>
<td><span><?php echo $calendar->formatEventTime($event->startTime,'dm'); ?></span></td>
<td><span><?php echo $calendar->formatEventTime($event->startTime,'time'); ?></span></td>
<td><?php echo $event->name; ?></td>
</tr>
<?php endforeach; ?>
</table>
include_once(WP_CAL_PLUGIN_DIR.'eventcal.class.php');
$calendar=新事件日历();
$events=$calendar->getMultipleEvents('5');
(...)
有没有一种方法可以在我的插件中调用函数,而不必包含WP插件并创建新的类实例?来自:
WordPress提供了钩子,允许你的插件“钩住”WordPress的其余部分;也就是说,在特定时间调用插件中的函数,从而启动插件。有两种挂钩:
* Modify database data
* Send an email message
* Modify what is displayed in the browser screen (admin or end-user)
实现这一点的基本步骤(详细描述如下)如下:
function email_friends($post_ID) {
$friends = 'bob@example.org,susie@example.org';
mail($friends, "sally's blog updated",
'I just put something on my blog: http://blog.example.com');
return $post_ID;
}
连接到WordPress
定义函数后,下一步是“钩住”或向WordPress注册它。为此,在插件文件的全局执行空间中调用add_action():
add_action ( 'hook_name', 'your_function_name', [priority], [accepted_args] );
add_action ( 'publish_post', 'email_friends' );
其中:
胡克的名字
WordPress提供的动作钩子的名称,它告诉你的函数应该与什么事件关联。
您的函数名
在hook_name指定的事件之后要执行的函数的名称。这可以是一个标准的php函数,WordPress核心中的函数,也可以是您在插件文件中定义的函数(如上面定义的“email\u friends”)。
优先
一个可选的整数参数,可用于指定与特定操作关联的函数的执行顺序(默认值:10)。较低的数字对应较早的执行,具有相同优先级的函数按照它们添加到操作中的顺序执行。
已接受的参数
一个可选的整数参数,用于定义函数可以接受多少个参数(默认值为1),这很有用,因为某些挂钩可以向函数传递多个参数。此参数在1.5.1版中是新的
在上面的示例中,我们将在插件文件中放置以下行:
add_action ( 'hook_name', 'your_function_name', [priority], [accepted_args] );
add_action ( 'publish_post', 'email_friends' );
要在模板内执行短代码,请使用函数
do_shortcode(“[my shortcode handle]”)
。您的短代码需要像普通代码()一样注册,然后才能在模板中使用它。任何属性、内部内容等也应该在那里
echo do_shortcode( '[my-shortcode foo="bar"]Shortcode content[/my-shortcode]' );
另外,请记住回显返回(或至少将其分配给变量),因为它只返回短代码的输出。为什么不包括WP插件并创建新的类实例?我想有一种更“WP正确”的方法来实现它-类似于WP short code。是的。在这种情况下,您应该注册一个短代码。:)但是短代码只在文本中使用,而不在PHP模板中使用?如果需要在模板中执行短代码,可以执行
do\u短代码('shortcode-handle')
。我知道挂钩。但这里没有触发器。加载特定模板时,我只是从DB表中检索数据。所以我认为约翰建议使用do_shortcode('shortcode-handle')
是最好的方法。