Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Explaining my goal: I would create the title by taking the first words of the post content. Ex: In the Admin interface would be the title field blank and the first 10 words of content would be sent as a title when creating a new post.

Thanks for any help.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

I have written a small plugin exactly for that some time ago. It hooks into 'save_post' and takes the first 20 characters as title if there is no title set already:

add_action( 'save_post', 't5_fix_empty_title', 11, 2 );

/**
 * Fills an empty post title from the first words of the post.
 *
 * @param  int    $post_id      Post ID
 * @param  object $post         Post object
 * @return void
 */
function t5_fix_empty_title( $post_id, $post )
{
    if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        or ! current_user_can( 'edit_post', $post_id )
        or ! empty ( $post->post_title )
        or empty ( $post->post_content )
        or wp_is_post_revision( $post )
    )
    { // Noting to do.
        return;
    }

    // Remove all tags and replace breaks whith white space.
    $no_tags = wp_strip_all_tags( $post->post_content, TRUE );

    // The post content contains just markup.
    if ( '' === $no_tags )
    {
        return;
    }

    $length = apply_filters( 't5_fix_empty_title_length', 20 );
    $words  = preg_split( "/\s+/", $no_tags, $length, PREG_SPLIT_NO_EMPTY );
    array_pop( $words );

    $title = implode( ' ', $words );
    // Add a no break space and an ellipsis at the end.
    $title = rtrim( $title, '.,!?…*' ) . ' …';

    wp_update_post( array ( 'ID' => $post_id, 'post_title' => $title ) );
}
share|improve this answer
    
Okay, buddy. I'll test your plugin and I say if it was what I needed. Thank you. –  BóbGCA May 19 '12 at 5:35
    
Great job toscho. One more detail (if not too much to ask, lol). This function would remove a tag that has the html content. Ex: <div class="mydivx">Paragraph 1</div> I would like to remove <div class="mydivx">. This div is part of the beginning (<div class="mydivx">Title of my post) –  BóbGCA May 19 '12 at 5:52
3  
@MichaelWilliam - you can use wp_strip_all_tags to remove the HTML tags. –  Stephen Harris May 19 '12 at 10:47
    
Thanks Stephen Haris, I'm just getting adapted to the small wp_strip_all_tags toscho plugin. Note that it also has the code"/[\n\r\t ]+/". –  BóbGCA May 19 '12 at 11:16
    
@StephenHarris Good hint, I made an update. –  toscho May 19 '12 at 15:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.