【问题标题】:WordPress publish_post hook not firing for custom post typeWordPress publish_post 挂钩未针对自定义帖子类型触发
【发布时间】:2015-02-21 04:06:00
【问题描述】:

我目前正在使用 WP Job Board Manager 插件做一些工作,我想创建一个在发布新工作时触发的函数。

我做的第一件事是创建通用钩子来找出帖子类型是什么:

function newJobAdded() {
    $posttype = get_post_type( $post );
    mail('email@email.com','new job published',$posttype);


 }
add_action( 'publish_post', 'newJobAdded' );

这给我发了一封电子邮件,告诉我帖子类型是:job_listing。 然后我创建了一个新函数,只有在自定义帖子类型为 job_listing

时才会触发
function newJobAdded() {

   $posttype = "job_listing";

   if ($post->post_type == $posttype) {
    mail('email@email.com','new job published','done new job publish');
   }


 }
add_action( 'publish_post', 'newJobAdded' );

但是,当我这样做时,什么也没有发生。我错过了一些简单和无聊的东西吗?

【问题讨论】:

  • Vidya LB 有最好的答案,因为您可以通过操作和类型来限制挂钩(发布职位发布 => 'publish_job_posting')。我只是想说你的第二个钩子不起作用,因为你没有在你的函数中传递 $post 变量,这应该在 add_action 调用中完成。当您在第一个函数中调用 get_post_type( $post ); 时,$post 实际上为空。它之所以有效,是因为您已经在您正在寻找的帖子上。
  • @JasonRoman 使用transition_post_status,您将获得更大的灵活性。在我的方法中,该函数仅在发布的新帖子以及帖子类型为选定类型时执行
  • 我认为这没有必要 - 只要发布了新的 job_posting 或将其状态更改为发布,就会触发 publish_job_posting

标签: php wordpress hook custom-post-type


【解决方案1】:

试试

function newJobAdded($ID, $post) {

}

而不是

function newJobAdded() {

}

参考:publish_post

【讨论】:

    【解决方案2】:

    “publish_post”操作是特定于帖子类型的。因此,如果您有自定义帖子类型,则需要更改您使用的挂钩。如果你的帖子类型是job_listing,你应该使用的钩子是publish_job_listing

    function newJobAdded($ID, $post ) {
        mail('email@email.com','new job published','done new job publish');
     }
    add_action( 'publish_job_listing', 'newJobAdded', 10, 2 );
    

    【讨论】:

    • 你能告诉我'10, 2'是干什么用的吗?
    • '10, 2' 分别代表优先级和参数个数,检查codex.wordpress.org/Function_Reference/add_action
    • 嘿,这很好用。但是,当用户已经在那里保存 job_listing 时,它也会触发。我可以将其更改为仅在初始发布时触发吗?非常感谢。
    • 尝试添加条件语句,例如 if( ( $post['post_status'] == 'publish' ) && ( $_POST['original_post_status'] != 'publish' ) )
    【解决方案3】:

    更通用的钩子是transition_post_status,它会在每次帖子状态发生变化时触发。您可以使用$old_status$new_status 检查帖子的先前状态和新状态,然后执行某些操作。

    对于新帖子,您可以这样:(需要 PHP 5.3+

    add_action( 'transition_post_status', function ( $new_status, $old_status, $post )
    {
    
        if( 'publish' == $new_status && 'publish' != $old_status && $post->post_type == 'my_post_type' ) {
    
            //DO SOMETHING IF NEW POST IN POST TYPE IS PUBLISHED
    
        }
    }, 10, 3 );
    

    编辑

    对于旧版本,请使用

    add_action( 'transition_post_status', 'so27613167_new_post_status', 10, 3 );
    function so27613167_new_post_status( $new_status, $old_status, $post )
    {
    
        if( 'publish' == $new_status && 'publish' != $old_status && $post->post_type == 'my_post_type' ) {
    
            //DO SOMETHING IF NEW POST IN POST TYPE IS PUBLISHED
    
        }
    }
    

    【讨论】:

    • 这给出:解析错误:语法错误,意外的 T_FUNCTION
    • 那么您使用的 PHP 版本早于 5.3。查看我的更新
    猜你喜欢
    • 2015-07-22
    • 2014-09-01
    • 2013-12-10
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多