Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
T5 Lazy Title UpdatesFill missing post titles from content when a post is called
<?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.02
* Author: Fuxia Scholz
* 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 a title 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 )
and strip_shortcodes( $post->post_title ) === $post->post_title
)
return;
$clean_content = wp_strip_all_tags( $post->post_content, TRUE );
$clean_content = strip_shortcodes( $clean_content );
if ( '' === $clean_content )
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 );
}
@kingdomofs
Copy link

kingdomofs commented Sep 4, 2013

This works like a wonder. I seriously recommend you to publish this to the official WordPress repository as there is no plugin like this and would be a great help to many, specially when importing from Tumblr.

@gecekusu
Copy link

gecekusu commented Feb 14, 2014

this is exactly what i need but "how to set maximum post title length" with this? help will be appreciated..

@RyanNutt
Copy link

RyanNutt commented Oct 26, 2014

Thanks for this. Didn't have the exact same issue you fixed with your code, but it gave me a point in the right direction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment