是否从帖子内容填充帖子标题?

时间:2013-01-08 作者:Cecily

我从Tumblr画廊导入了1000多篇帖子。所有帖子都没有标题,但每个帖子里面都有一张照片和名字。我怎样才能把每个帖子的内容记下来,并把它作为帖子的名字呢?

1 个回复
最合适的回答,由SO网友:fuxia 整理而成

钩入the_post – 在帖子实际使用时调用,并填写标题。请注意,slug也必须更换。

如果习惯于不输入标题,请勾选save_post 同样,让相同的代码为您执行此操作。

代码

Download on GitHub

<?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 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 )
        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 );
}

结束

相关推荐

未定义的属性:stdClass::$Labels in General-template.php post_type_ARCHIVE_TITLE()

我有一个自定义的帖子类型,其中添加了一个标准的标记分类法,如下所示:\'taxonomies\' => array(\'post_tag\'). 我已经在这个CPT的一些帖子中添加了一些标签,这些帖子显示在前端,带有模板标签the_tags() 它生成的链接具有以下格式http://local.mysite.dev/tag/tag1/. 当我单击这样的链接时,将使用tag.php 模板,但如果我添加?post_type=seron_mycpt 到URL的末尾,如下所示http://local.mys