publish_post called too early

时间:2016-06-06 作者:Shamim Hasan

我有一个元框来存放一些电子邮件地址,我在save\\u post hook中保存了值

add_action( \'save_post\', \'sm12_save_post\' );
function sm12_save_post( $postid ){
    update_post_meta( $postid, \'_some_email_address\', $_POST[\'some_email_address\'] );
}
现在我只想在这篇文章发布后才向这个电子邮件地址发送电子邮件。所以我用

add_action( \'publish_post\', \'sm12_publish_post\' );
function sm12_publish_post( $postid ){
$email = get_post_meta( $postid, \'_some_email_address\', true );

if( ! $email )
    return;

$sub = \'test subject\';
$mgs = \'test message\';

wp_mail( $email, $sub, $mgs );
}
如果帖子以“发布”以外的任何其他状态保存,则发布时会发送电子邮件,但如果帖子是直接发布,则无法发送电子邮件,因为在“保存帖子”之前调用了“发布帖子”,而meta在那里还不可用。如何仅在我的案例中发布时发送电子邮件?保存期间不应最后调用wp\\u transition\\u post\\u status()?

2 个回复
最合适的回答,由SO网友:Shamim Hasan 整理而成

如果有人需要,我会发布我的答案。

第一次保存元值

add_action( \'save_post\', \'sm12_save_post\' );
function sm12_save_post( $postid ){
/** some checks */
update_post_meta( $postid, \'_some_email_address\', $_POST[\'some_email_address\'] );
}
然后钩住两个save_postpublish_post

add_action( \'publish_post\', \'sm12_send_email\' );
add_action( \'save_post\', \'sm12_send_email\', 20 ); //After save meta value
function sm12_publish_post( $postid ){

/** some checks */

if( "publish" != get_post_status( $postid ) )
return;

$email = get_post_meta( $postid, \'_some_email_address\', true );

if( ! $email )
    return;

if( get_post_meta( $postid, \'_sm12_email_sent\', true ) )
  return;

$sub = \'test subject\';
$mgs = \'test message\';

if( wp_mail( $email, $sub, $mgs )) {
 update_post_meta( $postid, \'_sm12_email_sent\', time() );
 }
}

SO网友:Ismail

尝试此问题的解决方法,但不使用publish_post 挂钩(使用save_post)

add_action( \'save_post\', \'wpse228941_save_post\' );
function wpse228941_save_post( $post_id ) {
    if( defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE ) return;

    if ( "publish" == get_post_status( $post_id ) && ! get_post_meta( $post_id, "se_228941_mailed", 1 ) ) {
        do_action( "sm12_publish_post", $post_id );
        update_post_meta( $post_id, "se_228941_mailed", time() );
    }

}

add_action( \'sm12_publish_post\', \'sm12_publish_post\' );
function sm12_publish_post( $postid ){
    $email = get_post_meta( $postid, \'_some_email_address\', true );

    if( ! $email )
        return;

    $sub = \'test subject\';
    $mgs = \'test message\';

    wp_mail( $email, $sub, $mgs );
}
希望有帮助。