• All the posts I make have custom fields attached to it. I also made it so I can publish empty posts. I want to make a line of code when I create a post it checks to see if a certain custom field is empty if it is delete it if it isn’t publish it. I have this so far.

    function force_type_private($post)
    {
        $post['post_status'] = 'publish';
        return $post;
    }
    add_filter('wp_insert_post_data', 'force_type_private');
Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    For the ‘wp_insert_post_data’ filter, the post does not yet exist in the DB, nor does any meta (custom field) data exist there. The data from the post edit form resides in $_POST. A lot of it is passed to ‘wp_insert_post_data’ callbacks, but custom field data is not passed. Custom field data is not saved to the DB until after the post itself has been saved.

    So I think you’re saying that if some custom field value is not assigned, you want the insert post process aborted, is that right? From the ‘wp_insert_post_data’ callback, check the $_POST array for the crucial data. If it’s missing, execute wp_die() with an appropriate message.

    Thread Starter lex713

    (@lex713)

    @bcworkz how would I write a line of code that if the title equals auto draft delete it? I have it set up where if the field is empty it names it autodraft.

    Moderator bcworkz

    (@bcworkz)

    When that title gets assigned could impact the logic needed, as does if we only need to watch for new posts or both updated and new. Using the ‘wp_insert_post_data’ filter and assuming “autodraft” is assigned to $post['post_title'] and it’s a new insertion, this should be enough:

    if ($post['post_title'] = 'autodraft') wp_die('Post was not saved');
    return $post;

    If that doesn’t work, there was already a post saved to the DB and it really does need to be deleted. Instead of dying the process, call wp_delete_post( $post['ID'], false );

    That call really just changes the status to trash, it’s not truly removed from the DB. To fully remove the post, pass true as the second parameter.

    Thread Starter lex713

    (@lex713)

    
    function remove_if_empty ($post) {
    	if ($post['post_title'] = 'autodraft') 
    		{
    			wp_die('Post was not saved');
    			return $post;
    		}
    }
    add_filter('wp_insert_post_data', 'remove_if_empty');
    

    So I wrote this but every time I hit add new it goes to a page that says “Post was not saved.”

    Moderator bcworkz

    (@bcworkz)

    Move return $post; to outside and after the conditional. You don’t need it after dying, but you sure do need it when the condition is not fulfilled.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Deleting post if field is empty’ is closed to new replies.