特定自定义帖子类型的WP_UPDATE_POST

时间:2015-04-18 作者:Aabed Arjmand

首先,我很抱歉我的英语很差,当我升级一篇帖子时,这段代码将帖子slug更改为“profileid”costom字段值。。

add_action(\'save_post\', \'my_custom_slug\');
function my_custom_slug($post_id) {


     //Check it\'s not an auto save routine
    if ( defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE ) 
        return;
 //Perform permission checks! For example:
    if ( !current_user_can(\'edit_post\', $post_id) ) 
        return; 
    //If calling wp_update_post, unhook this function so it doesn\'t loop infinitely
    remove_action(\'save_post\', \'my_custom_slug\');
    //call wp_update_post update, which calls save_post again. E.g:
        wp_update_post(array(\'ID\' => $post_id, \'post_name\' =>get_post_meta($post_id,\'profileid\',true)));
    // re-hook this function
    add_action(\'save_post\', \'my_custom_slug\');
}
它工作得很好,但我如何才能将其仅用于特定的自定义帖子类型?我的自定义帖子类型是“masters”。。我用过这个,但不管用!有人能帮忙吗?

add_action(\'save_post\', \'my_custom_slug\');
function my_custom_slug($post_id) {


    $slug = \'masters\';
    // If this isn\'t a \'masters\' post, don\'t update it.
    if ( $slug != $post->post_type )
        return $post_id;


     //Check it\'s not an auto save routine
    if ( defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE ) 
        return;
 //Perform permission checks! For example:
    if ( !current_user_can(\'edit_post\', $post_id) ) 
        return; 
    //If calling wp_update_post, unhook this function so it doesn\'t loop infinitely
    remove_action(\'save_post\', \'my_custom_slug\');
    //call wp_update_post update, which calls save_post again. E.g:
        wp_update_post(array(\'ID\' => $post_id, \'post_name\' =>get_post_meta($post_id,\'profileid\',true)));
    // re-hook this function
    add_action(\'save_post\', \'my_custom_slug\');
}

3 个回复
最合适的回答,由SO网友:websupporter 整理而成

如果帖子不是特定的帖子类型,则可以停止执行该函数。您可以使用get_post_type() 为了这个。

if( \'masters\' != get_post_type( $post_id ) )
  return;

SO网友:fuxia

只是不要使用动作save_post, 使用"save_post_{$post->post_type}" 相反它之前就开火了save_post, 你会得到同样的信息。

职位类型示例masters:

add_action( \'save_post_masters\', \'my_custom_slug\', 10, 2 );

function my_custom_slug( $post_id, \\WP_Post $post ) {
}

SO网友:Meet Patel

/*仅检查您的帖子类型*/

    function your_function_name( $post_id ) {
        global $post;  

        //skip auto save

        //......

        if( $post->post_type == "your_post_type" ) {
                if( isset($_POST[\'your_post_id\']) ) { update_post_meta( $post->ID, \'your_post_id\', $_POST[\'your_post_id\'] );}
            }
}

结束

相关推荐