介绍50个 WordPress 动作挂钩(21-30)

在这个系列中,我们来看看 WordPress 的动作挂钩:一种可以让我们在应用程序中进行自定义执行的挂钩。在上一篇文章中,我们已经学习了11-20个挂钩,下面我们将继续学习更多。

在这一系列的文章中,我们将要介绍一些WordPress的动作(action)——是应用程序允许我们自定义执行的钩子(hook)。在最后的一篇文章中,我们已经学习了第二批的10个动作,也就是我们总共学习了20个动作了。

跟之前文章的风格一致,我们将会继续举例介绍另外的10个动作钩子。

好了,我们继续。

在执行get_posts()函数前操作它

pre_get_posts()动作(action)可以操作最重要的查询函数之一:get_posts()。

包含自定义文章类型到搜索结果

假如你维护着一个电影展示的博客,而且你需要能够对“电影”这种类型的文章进行搜索。按照下面的代码例子,你可以添加任何文章类型到搜索结果:

<?php
add_action( 'pre_get_posts', 'pre_get_posts_example' );
function pre_get_posts_example( $query ) {
    if ( ! is_admin() && $query->is_main_query() ) {
        if ( $query->is_search ) {
            $query->set( 'post_type', array( 'post', 'movie' ) );
        }
    }
}
// Example Source: http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
?>

现在你的博客中的搜索结果就可以包含“电影”这种文章类型了。

文章状态变化的监控

确实有很多关于文章状态变化的动作(action)——从草稿变为发布、定时发布、发布为私密等等。WordPress把这一系列的动作(action)定义为一个变量型的的钩子{$old_status}_to_{$new_status}

但是,如果你需要对所有的状态都做监控的话,你可以使用transition_post_status这个动作(action)。

当文章状态变化时通过邮件通知管理员

想象一下如果你的博客中有三个编辑者,你可能希望能得到每个文章的状态变化得信息。那么下面的代码你就可以用得到:

<?php
add_action( 'transition_post_status', 'transition_post_status_example', 10, 3 );
function transition_post_status_example( $new_status, $old_status, $post ) {
    if( $post->post_type !== 'post' ) {
        return;
    }
    $title      = $post->post_title;
    $to         = get_option( 'admin_email' );
    $subject    = 'Post status changed';
    $body       = "Hey,\n\nThe status of the post \"$title\" has been changed from \"$old_status\" to \"$new_status\".\n\nCheers!";
    wp_mail( $to, $subject, $body );
}
?>

给后台管理页面引入脚本

如果你需要引用一个JavaScript文件到管理员面板上中,那么admin_enqueue_scripts这个动作(action)就是为你准备的。这个小巧的动作(action)就是负责将脚本或者样式(css)引入到WordPress的仪表盘的。

为文章添加/编辑页面引入一段脚本

假设你创建了一个meta box,但是需要引入一段放在你的插件目录中的脚本使其能正常运行。你该怎么做呢?你不能把<script>这个标签直接写死到代码中,而是要使用下面例子的方式来做:

<?php
add_action( 'admin_enqueue_scripts', 'admin_enqueue_scripts_example' );
function admin_enqueue_scripts_example( $hook ) {
    if( 'edit.php' != $hook ) {
        return;
    }
    wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'myscript.js' );
}
// Example Source: http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts
?>

文章保存过程的控制

顾名思义,这个动作(action)是在一个文章被保存到数据库时的回调函数。

在文章发布或者定时发布时需要一个特色图片

我需要给我的每篇文章都设置一个特色图片,但有时候可能忘记这么做。你可以看看下面的解决方案:

<?php
add_action( 'save_post', 'save_post_example' );
add_action( 'admin_notices', 'admin_notices_example' );
function save_post_example( $post_id ) {
    // change to any custom post type 
    if( get_post_type( $post_id ) != 'post' ) {
        return;
    }
    if ( ! has_post_thumbnail( $post_id ) ) {
        // set a transient to show the users an admin message
        set_transient( 'has_post_thumbnail', 'no' );
        // unhook this function so it doesn't loop infinitely
        remove_action( 'save_post', 'wpds_check_thumbnail' );
        // update the post set it to draft
        wp_update_post( array( 'ID' => $post_id, 'post_status' => 'draft' ) );
        add_action( 'save_post', 'wpds_check_thumbnail' );
    } else {
        delete_transient( 'has_post_thumbnail' );
    }
}
function admin_notices_example() {
    // check if the transient is set, and display the error message
    if ( get_transient( 'has_post_thumbnail' ) == 'no' ) {
        echo '<div id="message" class="error"><p>You must select a featured image for your post.</p></div>';
        delete_transient( 'has_post_thumbnail' );
    }
}
// Example Source: http://wpdevsnippets.com/require-post-thumbnail-uploaded-before-publishing/
?>

虽然代码有点长,但是方案还是好滴,对不?

为文章类型添加Meta 组件

Meta组件(Meta boxes)是WordPress号称全球最具有可扩展性的内容管理系统的一个基础。确实是这样的,你可以创建任何内容作为一个meta组件然后让你的用户借此来添加数据。Add_meta_boxes这个动作是创建Meta组件的主要钩子。

创建一个简单的Meta组件

我们将会添加一个add_meta_box()关联到add_meta_boxes动作(action)上:

<?php
// action for the 'post' post type
add_action( 'add_meta_boxes', 'add_meta_boxes_example', 10, 2 );
// action for the 'event' post type
add_action( 'add_meta_boxes_event', 'add_meta_boxes_example', 10, 2 );
function add_meta_boxes_example( $post_type, $post ) {
    add_meta_box( 
        'my-meta-box',
        __( 'My Meta Box' ),
        'render_my_meta_box',
        'post',
        'normal',
        'default'
    );
}
function render_my_meta_box() {
    // code to create the meta box
}
// Example Source: http://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes
?>

注:如果你想要学习更多有关创建自定义小组件的内容可以查找Christopher Davis写的教程

玩转“概览”

“概览”是每个WordPress安装后的第一个小工具。你可以使用activity_box_end动作(action)来定制这个小工具。

把你的联系信息放到“概览”中

假如你是一个WordPress自由专栏的开发者,你希望你的客户能够记住你的手机号。通过下面的例子:你可以把你的手机号写到这块:

<?php
add_action( 'activity_box_end', 'activity_box_end_example' );
function activity_box_end_example() {
   _e( "If you have any questions, you can reach the webmaster at +1-999-526-0130. Have a nice day!" );
}
?>

修改默认的“功能”小工具

WordPress默认提供了很多小组件,“功能”小组件就是其中的一个。通过wp_meta这个动作(action),我们就可以来定制自己的小工具。

添加一个“Twitter关注”连接到“功能”小工具上

就算“功能”小组件不是WordPress中最流行的一个,但是你可以给它添加很多有用的功能,例如:

<?php
add_action( 'wp_meta', 'wp_meta_example' );
function wp_meta_example() {
    $twitter_username = 'BarisUnver';
    echo '<li>Follow us on Twitter:<a href="https://twitter.com/' . $twitter_username . '">' . $twitter_username . '</a></li>';
}
?>

当然,这只是一个很简单的例子,但是至少是可用的。

玩转“仪表盘”

“仪表盘”是WordPress安装之后一个主要的管理面板。通过wp_dashboard_setup动作(action)你可以像下面这样定制它。

显示最新的 Disqus 评论

译者注:Disqus 是国外一家第三方社会化评论系统

如果你使用Disqus来管理你的评论,并且想要在仪表盘中看到最新的评论,你可以使用下面的代码片段来增加一个小组件:

<?php
add_action( 'wp_dashboard_setup', 'wp_dashboard_setup_example' );
function wp_dashboard_setup_example() {
    $disqus_username = 'USERNAME';
    $number_of_comments = 5;
    wp_add_dashboard_widget( 'disqus-feed', 'Latest Disqus Comments', 'acme_display_disqus_comments' );
}
function acme_display_disqus_comments() {
    echo '<div id="recentcomments" class="dsq-widget">' . '<script src="//' . $disqus_username . '.disqus.com/recent_comments_widget.js?num_items=' . $number_of_comments . '"></script></div>';
}
?>

改变$disqus_username $number_of_comments这两个变量就能看到效果。

设置当前用户

来看一下插件式函数,WordPress是这样来定义的:

这些函数能被插件替代。如果插件不重新定义这些函数,就会使用原有的。

wp_set_current_user这个小巧的函数就是其中的一个,可以通过用户的ID或者名称(name)来修改当前用户信息。

为订阅者移除工具栏

我们现在不会去更改用户,而是使用动作(action)钩子的优势,来检查当前用户的能力(capabilities),如果这个用户是订阅者,就禁用工具栏:

<?php
add_action( 'set_current_user', 'set_current_user_example' );
function set_current_user_example() {
    if ( ! current_user_can( 'edit_posts' ) ) {
        show_admin_bar( false );
    }
}
?>

插件加载

如果你想要在WordPress加载完成插件之后做一些事情的话可以使用plugins_loaded这个动作(action)。

开始你的插件

正确初始化并运行插件的方法是把它的主要函数都挂载到plugins_loaded这个动作(action)中。这里我们给出了一个例子:

<?php
add_action( 'plugins_loaded', 'plugins_loaded_example' );
function plugins_loaded_example() {
    add_action( 'wp_footer', 'display_message', 100 );
}
function display_message() {
    echo '<p>This is some dummy text!</p>';
}
// Example Source: http://www.scratchinginfo.com/common-wordpress-action-hooks-for-plugin-development/
?>

如果需要一个更好的例子,你是可以做到的,那么你应该看一看Tom MacFarlin’s的“WordPress Plugin Boilerplate”这本书,哪里有你需要构建一个WordPress插件的所有基于面向对象的编程思想的内容。

小结

我们已经介绍完了50个动作(action)的第三部分。希望你能喜欢这部分内容并且从中学习到了新的知识。下一部分再见!

同时我也希望能得到您的反馈。您对这些内容有什么想法?请在下面留言,如果你喜欢这些内容的话也别忘了分享一下!

原文出自:http://code.tutsplus.com/tutorials/fifty-actions-of-wordpress-50-examples-21-to-30–cms-21580