Auto Populate Excerpt Field

时间:2012-01-29 作者:Towfiq

如何用帖子内容的前15个单词自动填充摘录字段?我找到了以下片段:

function wps_excerpt_content( $content ) {
    $content = "YOUR EXCERPT HERE";
    return $content;
}
add_filter( \'default_excerpt\', \'wps_excerpt_content\' );
但我不知道如何根据需要修改它。有什么帮助吗?

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

使用excerpt_length 滤器

function my_excerpt_lenght( $length ) {
    return 15;
}
add_filter( \'excerpt_length\', \'my_excerpt_lenght\', 999 );

SO网友:brasofilo

OP代码段用于设置创建帖子时的默认摘录:http://example.com/wp-admin/post-new.php. 因此,它对所需的操作没有用处

起初,我想到save_post 操作,但发现了一个很好的提示this answer from Eugene Manuilov.

以下代码自动填充post_excerpt 无论何时创建或保存帖子if it had no previous excerpt
请注意,摘录的创建可以大大改进,因为它既不区分URL,也不区分短词。

// Define the custom excerpt length
$wpse_40574_custom_excerpt_length = 15;

add_filter( \'wp_insert_post_data\', \'wpse_40574_populate_excerpt\', 99, 2 );

/** 
 * Checks if the the post has excerpt or not
 * Code reference: https://wordpress.stackexchange.com/a/52897/12615
 */
// 
function wpse_40574_populate_excerpt( $data, $postarr ) 
{   
    global $wpse_40574_custom_excerpt_length;
    
    // check if it\'s a valid call
    if ( !in_array( $data[\'post_status\'], array( \'draft\', \'pending\', \'auto-draft\' ) ) && \'post\' == $data[\'post_type\'] ) 
    {
        // if the except is empty, call the excerpt creation function
        if ( strlen($data[\'post_excerpt\']) == 0 ) 
            $data[\'post_excerpt\'] = wpse_40574_create_excerpt( $data[\'post_content\'], $wpse_40574_custom_excerpt_length );
    }

    return $data;
}

/** 
 * Returns the original content string if its word count is lesser than $length, 
 * or a trimed version with the desired length.
 * Reference: see this StackOverflow Q&A - http://stackoverflow.com/q/11521456/1287812
 */
function wpse_40574_create_excerpt( $content, $length = 20 )
{
    $the_string = preg_replace( \'#\\s+#\', \' \', $content );
    $words = explode( \' \', $the_string );

    /**
     * The following is a more efficient way to split the $content into an array of words
     * but has the caveat of spliting Url\'s into words ( removes the /, :, ., charachters )
     * so, not very useful in this context, could be improved though.
     * Note that $words[0] has to be used as the array to be dealt with (count, array_slice)
     */
    //preg_match_all( \'/\\b[\\w\\d-]+\\b/\', $content, $words );

    if( count($words) <= $length ) 
        $result = $content;
    else
        $result = implode( \' \', array_slice( $words, 0, $length ) );

    return $result;
}
注意Example of default_excerpt filter usage:

add_filter( \'default_excerpt\', \'wpse_40574_excerpt_content\', 10, 2 );

function wpse_40574_excerpt_content(  $post_excerpt, $post  ) 
{
    // Do nothing if not the correct post type
    // http://codex.wordpress.org/Post_Types
    if( \'post\' != $post->post_type )
        return;
        
    $post_excerpt = "DEFAULT EXCERPT FOR POSTS OF THE TYPE -POST-";

    return $post_excerpt;
}

结束