您可以使用摘录来实现这一点,但摘录在默认情况下会过滤所有HTML标记。要解决这个问题,我们需要对其进行过滤并添加新的逻辑。
这将根据您的需要过滤摘录以进行更改:
您必须在主题中添加此功能functions.php
functions.php
function wpse_allowedtags() {
//The Tags you put here will not be removed, therefore if you want to include strong HTML tag, you should add it here as shown:
return \'<strong>\';
}
if ( ! function_exists( \'wpse_custom_wp_trim_excerpt\' ) ) :
function wpse_custom_wp_trim_excerpt($wpse_excerpt) {
$raw_excerpt = $wpse_excerpt;
if ( \'\' == $wpse_excerpt ) {
$wpse_excerpt = get_the_content(\'\');
$wpse_excerpt = strip_shortcodes( $wpse_excerpt );
$wpse_excerpt = apply_filters(\'the_content\', $wpse_excerpt);
$wpse_excerpt = str_replace(\']]>\', \']]>\', $wpse_excerpt);
$wpse_excerpt = strip_tags($wpse_excerpt, wpse_allowedtags()); /*IF you need to allow just certain tags. Delete if all tags are allowed */
/*Set the excerpt word count and only break after sentence is complete.
You can set this to any number you want in this case we\'ll use 300
words. */
$excerpt_word_count = 300;
$excerpt_length = apply_filters(\'excerpt_length\', $excerpt_word_count);
$tokens = array();
$excerptOutput = \'\';
$count = 0;
// Divide the string into tokens; HTML tags, or words, followed by any whitespace in order to clean the not allowed HTML tags.
preg_match_all(\'/(<[^>]+>|[^<>\\s]+)\\s*/u\', $wpse_excerpt, $tokens);
foreach ($tokens[0] as $token) {
if ($count >= $excerpt_length && preg_match(\'/[\\,\\;\\?\\.\\!]\\s*$/uS\', $token)) {
// Limit reached, continue until , ; ? . or ! occur at the end
$excerptOutput .= trim($token);
break;
}
// Add words to complete sentence
$count++;
// Append what\'s left of the token
$excerptOutput .= $token;
}
$wpse_excerpt = trim(force_balance_tags($excerptOutput));
if ( $count < 0) {
$excerpt_end = \' <a href="\'. esc_url( get_permalink() ) . \'">\' . \' » \' . sprintf(__( \'Reed more: %s »\', \'wpse\' ), get_the_title()) . \'</a>\';
$excerpt_more = apply_filters(\'excerpt_more\', \' \' . $excerpt_end);
$wpse_excerpt .= $excerpt_more; /*Add read more in new paragraph */
}
$wpse_excerpt .= \' [...]\';
return $wpse_excerpt;
}
return apply_filters(\'wpse_custom_wp_trim_excerpt\', $wpse_excerpt, $raw_excerpt);
}
endif;
remove_filter(\'get_the_excerpt\', \'wp_trim_excerpt\');
add_filter(\'get_the_excerpt\', \'wpse_custom_wp_trim_excerpt\');
之后,您只需调用主题所需模板文件中的非注册用户的\\u摘录:(请记住,它之前已过滤为包含300个单词)
// The user is logged in, display the full content
if(is_user_logged_in()){
the_content();
}else{
// show the_excerpt
<?php echo get_the_excerpt() ?>
}