Hook into the_post
– called when the post is actually used – and fill the title. Be aware the slug has to be changed too.
If you are used not to enter a title, hook into save_post
too, and let the same code do this for you.
The code
<?php
/**
* Plugin Name: T5 Lazy Title Updates
* Description: Fill missing post titles from content when a post is called
* Plugin URI:
* Version: 2013.01.08
* Author: Thomas Scholz
* Author URI: http://toscho.de
* Licence: MIT
* License URI: http://opensource.org/licenses/MIT
*/
add_action( 'the_post', 't5_lazy_title_update' );
add_action( 'save_post', 't5_lazy_title_update_save', 10, 2 );
/**
* Add atitle when the post is called in setup_postdata().
*
* @wp-hook the_post
* @param object $post
* @return void
*/
function t5_lazy_title_update( $post )
{
if ( ! empty ( $post->post_title )
or '' === $clean_content = wp_strip_all_tags( $post->post_content, TRUE )
)
return;
$words = preg_split( "/\s+/", $clean_content, 40, PREG_SPLIT_NO_EMPTY );
$title = implode( ' ', $words );
$title = rtrim( $title, '.;,*' );
$slug = wp_unique_post_slug(
sanitize_title_with_dashes( $title ),
$post->ID,
$post->post_status,
$post->post_type,
$post->post_parent
);
wp_update_post(
array (
'ID' => $post->ID,
'post_title' => $title,
'post_name' => $slug
)
);
// $post is passed by reference, so we update this property in realtime
$post->post_title = $title;
$post->post_name = $slug;
}
/**
* Fill title from post content on save
*
* @wp-hook save_post
* @param int $post_ID
* @param object $post
* @return void;
*/
function t5_lazy_title_update_save( $post_ID, $post )
{
t5_lazy_title_update( $post );
}