public
Created

Plugin Fix Empty Titles

  • Download Gist
fix-empty-titles.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
<?php # -*- coding: utf-8 -*-
/*
Plugin Name: Fix Empty Titles
Description: Replaces missing titles with the first characters from post body.
Version: 1.1
Required: 3.2
Author: Thomas Scholz
Author URI: http://toscho.de
License: GPL
 
Based on an idea of Konstantin Kovshenin. See
http://kovshenin.com/2011/10/wordpress-posts-without-titles-in-rss-feeds-3621/
*/
/**
* , Copyright (C) 2011 Thomas Scholz
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
 
! defined( 'ABSPATH' ) and exit;
 
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 ) );
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.