0

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.

0

1 Answer 1

3

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 ) );
}
5
  • Okay, buddy. I'll test your plugin and I say if it was what I needed. Thank you.
    – BobGCA2
    Commented May 19, 2012 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)
    – BobGCA2
    Commented May 19, 2012 at 5:52
  • 3
    @MichaelWilliam - you can use wp_strip_all_tags to remove the HTML tags. Commented May 19, 2012 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 ]+/".
    – BobGCA2
    Commented May 19, 2012 at 11:16
  • @StephenHarris Good hint, I made an update.
    – fuxia
    Commented May 19, 2012 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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