wordpress钩子:掌握对象和名称空间方法
挂钩是WordPress开发的基础。 先前的SitePoint文章探索了钩子基础知识,动作和过滤器之间的区别以及替代事件射击方法。本文着重于挂钩实例化类方法和在WordPress挂钩系统中导航命名空间。
>挂钩对象方法:广告管理器示例
想象一下构建广告管理器插件。 您将使用用于不同广告网络的方法创建一个AdManager
>类。
<code class="language-php">class AdManager { public function adsense() { ?> <ins data-ad-client="ca-pub-xxxxxxxxxxxxxxxx" data-ad-slot="6762452247" style="display:inline-block;width:336px;height:280px"></ins> (adsbygoogle = window.adsbygoogle || []).push({}); <?php } public function buysellads() { // ... } public static function get_instance() { static $instance = null; if ( $instance == null ) { $instance = new self(); } return $instance; } }</code>
>将adsense
的方法挂接到before_post_content
>操作(例如,在主题的functions.php
>中),您需要类的实例:
add_action( 'before_post_content', array( AdManager::get_instance(), 'adsense' ) );
使用Singleton方法(get_instance()
)提供了一种干净的方法来管理类实例。
>名称空间和WordPress挂钩系统
> WordPress挂钩系统早于名称空间。 挂接名称的函数和方法需要仔细注意。
考虑AdManager
>>>> SitePointPlugin
的类:
<code class="language-php">namespace SitePoint\Plugin; class AdManager { // ... }</code>要挂接其
方法,请先预留名称空间:adsense
add_action( 'before_post_content', array( SitePointPluginAdManager::get_instance(), 'adsense' ) );
如果
>
add_action
<code class="language-php">namespace SitePoint\Plugin; function google_site_verification() { echo '<meta content="ytl89rlFsAzH7dWLs_U2mdlivbrr_jgV4Gq7wClHDUJ8" name="google-site-verification">'; } add_action( 'wp_head', 'SitePoint\Plugin\google_site_verification' );</code>
>注册卸载挂钩的挂钩需要类似的护理。 无法充分限定班级名称可能会导致意外行为。 即使
和类都在同一命名文件文件中,始终预定名称空间。>
register_uninstall_hook
结论
了解如何处理WordPress挂钩系统中的对象方法和名称空间对于构建强大的插件和主题至关重要。 虽然由于系统的历史背景而存在一些怪癖,但仔细注意细节可确保平稳整合。
>以上是了解WordPress钩系统中的名称空间的详细内容。更多信息请关注PHP中文网其他相关文章!