Question

I have a custom post type with only 3 custom fields in it.

$post_types = get_post_meta($post->ID,'post_types',true);
$post_taxonomies = get_post_meta($post->ID,'post_taxonomies',true);
$post_terms = get_post_meta($post->ID,'post_terms',true);

I want to check if already exist post with this $post_types value, and if exist -> show message without publishing.

I created a metabox for this custom fields, which already have function for save_post action hook.

function sidebars_meta_save( $id )  {  
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;  

    if( !isset( $_POST['sidebars_nonce'] ) || !wp_verify_nonce( $_POST['sidebars_nonce'], 'save_sidebars_meta' ) ) return;  
    if( !current_user_can( 'edit_post' ) ) return;  

    $allowed = array(  
        'p' => array()  
    );      

    if(isset( $_POST['post_terms'] )){
                    //check_exist_term - simple boolean function which check if 
                    //a post with this term already exist
        if(!check_exist_term($_POST['post_terms'])){
            if( isset( $_POST['post_types'] ) ){  
                update_post_meta( $id, 'post_types', wp_kses( $_POST['post_types'], $allowed ) ); 
            }
            if( isset( $_POST['post_taxonomies'] ) ) { 
                update_post_meta( $id, 'post_taxonomies', wp_kses( $_POST['post_taxonomies'], $allowed ) );
            }
                update_post_meta( $id, 'post_terms', wp_kses( $_POST['post_terms'], $allowed ) );
            }
        }else{
                        //if I will use wp_delete_post here, the message will not show
            //wp_delete_post($id);
            //wp_redirect('post-new.php?post_type=sidebars');
            //exit;
        }
    }
}  
add_action( 'save_post', 'sidebars_meta_save' );  

My redirect location function :

function sidebars_redirect_location($location,$post_id){
if( isset( $_POST['post_types'] ) ){  
    if(check_exist_term($_POST['post_terms'])){
        $status = get_post_status( $post_id );
        $location = add_query_arg('message', 21, $location);
                    //if I will use wp_delete_post here, I will be not able 
                    //to return to post edit page, because page will be already deleted
    }
}
return $location;
}
add_filter('redirect_post_location','sidebars_redirect_location',10,2);

My post updated messages function :

function sidebars_custom_messages($messages){
$messages['sidebars'][21] = 'Looks like you tried publishing a post with term which already exist!';
return $messages;
}    
 add_filter('post_updated_messages', 'sidebars_custom_messages');    

1) Where I should use wp_delete_post() If I want to first of all to show a message that this post already exist and just then delete this post and stay on this page? 2) How to show red message instead of yellow?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top