本文介绍了如何防止Wordpress在摘录中剥离HTML标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用wp_trim_words修剪我的主页上的一些摘录。它工作得很好,只是它从摘录中剥离了HTML标签。我需要能够使粗体摘录的某些部分(使用< strong> )。按照的说明,我尝试删除wp_trim_words函数并将其替换使用下面的代码替换 $ text = strip_tags(原始的WP函数)中的 $ text = wp_strip_all_tags($ text); $ text,'< strong>,); 。但是这打破了网站。

  //删除Reverie Trim Words 
function remove_trim_words(){
remove_filter ('get_the_excerpt','wp_trim_words');
add_filter('get_the_excerpt','oakwood_trim_words');
}

//替换幻想修饰词
函数oakwood_trim_words($ text,$ num_words = 55,$ more = null){
if(null === $ more)
$ more = __('& hellip;');
$ original_text = $ text;
$ text = strip_tags($ text,'< strong>',);
/ *译员:如果您的字数是基于单个字符(东亚字符),
输入字符。否则,输入文字。不要翻译成你自己的语言。 * /
if('characters'== _x('words','word count:words or characters?')&&preg_match('/ ^ utf\?8 $ / i',get_option ('blog_charset'))){
$ text = trim(preg_replace(/ [\\\
\r\t] + /,'',$ text),'');
preg_match_all('/./u',$ text,$ words_array);
$ words_array = array_slice($ words_array [0],0,$ num_words + 1);
$ sep ='';
} else {
$ words_array = preg_split(/ [\\\
\r\t] + /,$ text,$ num_words + 1,PREG_SPLIT_NO_EMPTY);
$ sep ='';

if(count($ words_array)> $ num_words){
array_pop($ words_array);
$ text = implode($ sep,$ words_array);
$ text = $ text。 $以上;
} else {
$ text = implode($ sep,$ words_array);
}
/ **
*文字被剪裁后,过滤文字内容。
*
* @since 3.3.0
*
* @param string $ text修剪后的文本。
* @param int $ num_words修剪文本的字数。缺省值5.
* @param字符串$ more可选字符串,用于追加到修剪文本的末尾,例如&安培; hellip ;.
* @param string $ original_text修剪之前的文本。
* /
返回apply_filters('oakwood_trim_words',$ text,$ num_words,$ more,$ original_text);


解决方案

完整指南EXCERPTS



我最近回答了一些关于摘录的问题,所以我会尽可能详细地给出解释。



HTML标记/格式

首先不包含任何参数,所以不能传递给它。 In是一个事实: the_excerpt()将内容剪裁成55个单词,所有html标签在返回文本之前都被剥离。 the_excerpt()位于。为了在摘录中允许某些或全部的html标签,必须创建一个新的摘录。

首先,原始函数需要先被移除,然后新功能需要挂钩到。请注意,这个新的摘录在模板文件中仍然可以被调用为 the_excerpt(),不需要改变它。 get_the_excerpt()位于。


$ b 摘录使用,第2355行。 remove_filter('get_the_excerpt','wp_trim_excerpt');

您现在可以将您的新摘录添加到 get_the_excerpt

  add_filter('get_the_excerpt','wpse_custom_wp_trim_excerpt'); 

为了允许html标签/格式化,我们需要指定您需要允许的标签。您可以使用下面的 strip_tags 语句来实现该功能

  $ wpse_excerpt = strip_tags($ wpse_excerpt,wpse_allowedtags()); 

第二个参数 wpse_allowedtags()是用于添加标签的小函数 the_excerpt()将允许。有关有效HTML5标签的完整列表,请查看。这里是函数,添加任何HTML标记到这个,你需要允许/保持

 函数wpse_allowedtags(){
//将自定义标签添加到此字符串
return< script>,< style>,< br>,< em>,< i>< ul>,< ol>< ;李>,< a取代;,< p为H.,< IMG>,<视频>,<音频>';





$ b如果你需要允许所有的HTML标签,也就是说不需要剥离标签, strips_tags()函数可以完全省略/删除。 b
$ b

但是,当html标签被允许的时候,这些标签会被统计为单词,所以对于带有标签和不带标签的片段来说, 。为了纠正这种情况,您需要首先从实际字数中移除这些标签,以便只计算字数。



我已经写了一个摘录,允许所有标签,将单词作为单词进行计数,然后在设定的单词数量之后完成一个句子(不会裁剪文本中间句子),并在最后一个单词之后添加一个阅读更多文本。



这是完整的代码

pre $函数wpse_allowedtags(){
//添加自定义标签到这个字符串
return'< script>,< style>,< em>,< i>,< ul>,< ol>,< a> ; p为H.,< IMG>,<视频>,<音频>';

$ b $ if(!function_exists('wpse_custom_wp_trim_excerpt')):

函数wpse_custom_wp_trim_excerpt($ wpse_excerpt){
global $ post;
$ 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(']]>',']]& gt;',$ wpse_excerpt);
$ wpse_excerpt = strip_tags($ wpse_excerpt,wpse_allowedtags()); / *如果你需要只允许某些标签。删除所有标签是否被允许* /

//设置摘录字数并且只在句子完成后中断。
$ excerpt_word_count = 75;
$ excerpt_length = apply_filters('excerpt_length',$ excerpt_word_count);
$ tokens = array();
$ excerptOutput ='';
$ count = 0;

//将字符串划分为令牌; HTML标签或单词,后跟任何空格
preg_match_all('/(< [>] +> | [^<> +])\ s * / u', $ wpse_excerpt,$ tokens);
$ b foreach($ tokens [0] as $ token){

if($ count> = $ excerpt_word_count&& preg_match('/ [\, \\; \ \\\!] \s * $ / uS',$ token)){
//达到的限制,继续直到; ? 。要么 !发生在最后
$ excerptOutput。= trim($ token);
break;
}

//添加单词来完成句子
$ count ++;

//追加令牌的剩余部分
$ excerptOutput。= $ token;
}

$ wpse_excerpt = trim(force_balance_tags($ excerptOutput));

$ excerpt_end ='< a href ='。esc_url(get_permalink())。'>'。 '& nbsp;& raquo;& nbsp;'。 sprintf(__('了解更多关于:%s& nbsp;&;& raquo;','wpse'),get_the_title())。 < / A>;
$ excerpt_more = apply_filters('excerpt_more',''。$ excerpt_end);

// $ pos = strrpos($ wpse_excerpt,'< /');
// if($ pos!== false)
//最后一个HTML标记
// $ wpse_excerpt = substr_replace($ wpse_excerpt,$ excerpt_end,$ pos,0); / *添加阅读旁边的最后一个单词* /
// else
//在内容
$ wpse_excerpt。= $ excerpt_end; / *添加更多新的段落* /

返回$ 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');

您可以从需要额外的函数中删除'//'。 b
$ b

自定义提示长度

有时您需要显示不同长度的简单摘录,写每个帖子/功能/页面的摘录。这是一个很好的小函数,使用 wp_trim_words

  function wpse_custom_excerpts($限制){
return wp_trim_words(get_the_excerpt(),$ limit,'< a href ='。esc_url(get_permalink())。'>'。'& nbsp;…'。 __('Read more& nbsp;& raquo;','wpse')。'< / a>');



$ b $ p
$ b

这个小函数的作用是把 get_the_excerpt 修剪到由用户设置的 $ limit ,并在最后使用read more链接返回文本。



您可以在您的模板中调用此摘录

  echo wpse_custom_excerpts($限制); 

其中 $ limit ,所以30字的摘录将是

  echo wpse_custom_excerpts(30); 

只要记住一件事,如果您将限制设置为55字以上,只需要55个字将被退还,因为摘录只有55个字的长度。如果需要更长的摘录,请改用 get_the_content

p>

如果您只需要改变 the_excerpt()的长度,您可以使用下面的函数:

  function wpse_excerpt_length($ length){
return 20;
}
add_filter('excerpt_length','wpse_excerpt_length',999);

请记住,您需要设置大于10的优先级,以便在默认情况下执行自定义函数。

添加阅读更多链接



[...] 在最后不可点击。为了在hellips的位置添加一个阅读更多的文本,使用这个函数
$ b $ pre $函数wpse_excerpt_more($ more){
return'< a class =read-morehref ='。get_permalink(get_the_ID())。'>'。 __('阅读更多','你的文本域')。 < / A>;
}
add_filter('excerpt_more','wpse_excerpt_more');

编辑

第一段



b
$ b

这是一个让HTML标签保持完整的函数,在摘录结尾添加一个Read More链接,并在第一段之后对摘录进行修剪。

  if(!function_exists('wpse0001_custom_wp_trim_excerpt')):

function wpse0001_custom_wp_trim_excerpt($ wpse0001_excerpt){
global $ post ;
$ raw_excerpt = $ wpse0001_excerpt;
if(''== $ wpse0001_excerpt){

$ wpse0001_excerpt = get_the_content('');
$ wpse0001_excerpt = strip_shortcodes($ wpse0001_excerpt);
$ wpse0001_excerpt = apply_filters('the_content',$ wpse0001_excerpt); ($ wpse0001_excerpt,0,strpos($ wpse0001_excerpt,'< / p>)+ 4);
$ wpse0001_excerpt = str_replace(']]>',']]& gt;',$ wpse0001_excerpt);

$ excerpt_end ='< a href ='。esc_url(get_permalink())。'>'。 '& nbsp;& raquo;& nbsp;'。 sprintf(__('Read more about:%s& nbsp;& raquo;','pietergoosen'),get_the_title())。 < / A>;
$ excerpt_more = apply_filters('excerpt_more',''。$ excerpt_end);

// $ pos = strrpos($ wpse0001_excerpt,'< /');
// if($ pos!== false)
//在最后的HTML标签里面
// $ wpse0001_excerpt = substr_replace($ wpse0001_excerpt,$ excerpt_end,$ pos,0);
// else
//在内容
$ wpse0001_excerpt。= $ excerpt_end;

返回$ wpse0001_excerpt;


return apply_filters('wpse0001_custom_wp_trim_excerpt',$ wpse0001_excerpt,$ raw_excerpt);
}

endif;

remove_filter('get_the_excerpt','wp_trim_excerpt');
add_filter('get_the_excerpt','wpse0001_custom_wp_trim_excerpt');


I am using wp_trim_words to trim some excerpts on my homepage. It's working fine except that it's stripping the HTML tags from the excerpts. I need to be able to make certain pieces of the excerpt bold (using <strong>). Following the instructions here, I tried removing the wp_trim_words function and replacing it with a new one using the following code, which replaces $text = wp_strip_all_tags( $text ); from the original WP function with $text = strip_tags($text, '<strong>',);. But this breaks the site. What am I doing wrong?

    // Remove Reverie Trim Words
function remove_trim_words() {
    remove_filter('get_the_excerpt', 'wp_trim_words');
    add_filter('get_the_excerpt', 'oakwood_trim_words');
}

// Replace Reverie Trim Words
function oakwood_trim_words( $text, $num_words = 55, $more = null ) {
    if ( null === $more )
        $more = __( '&hellip;' );
    $original_text = $text;
    $text = strip_tags($text, '<strong>',);
    /* translators: If your word count is based on single characters (East Asian characters),
       enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
    if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
        $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
        preg_match_all( '/./u', $text, $words_array );
        $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
        $sep = '';
    } else {
        $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
        $sep = ' ';
    }
    if ( count( $words_array ) > $num_words ) {
        array_pop( $words_array );
        $text = implode( $sep, $words_array );
        $text = $text . $more;
    } else {
        $text = implode( $sep, $words_array );
    }
    /**
     * Filter the text content after words have been trimmed.
     *
     * @since 3.3.0
     *
     * @param string $text          The trimmed text.
     * @param int    $num_words     The number of words to trim the text to. Default 5.
     * @param string $more          An optional string to append to the end of the trimmed text, e.g. &hellip;.
     * @param string $original_text The text before it was trimmed.
     */
    return apply_filters( 'oakwood_trim_words', $text, $num_words, $more, $original_text );
}
解决方案

COMPLETE GUIDE TO EXCERPTS

I've recently answered a few questions regarding excerpts, so I' going to give a detailed explanation covering as much as I can.

HTML TAGS/FORMATTING

the_excerpt() first of all doesn't except any parameters, so nothing can be passed to it. In is a fact that the_excerpt() trims the content to 55 words, and all html tags are stripped before returning the text. the_excerpt() is located in wp-includes/post-template.php. To allow certain or all html tags in the excerpt, a new excerpt have to be created.

First of all, the original function needs to be removed first, and then the new function needs to be hooked to get_the_excerpt. Please take note, this new excerpt will still be callable as the_excerpt() in template files, no need to change that. get_the_excerpt() is located in wp-includes/post-template.php.

The excerpt uses wp_trim_excerpt to return the trimmed text, so we need to remove wp_trim_excerpt first from the excerpt filter. wp_trim_excerpt() is located in wp-includes/formatting.php, line 2355. This is how:

remove_filter('get_the_excerpt', 'wp_trim_excerpt');

You can now add your new excerpt to get_the_excerpt

add_filter('get_the_excerpt', 'wpse_custom_wp_trim_excerpt');

To allow html tags/formatting, we will need to specify which tags you will need to allow. You can use the following strip_tags statement to achieve that

$wpse_excerpt = strip_tags($wpse_excerpt, wpse_allowedtags());

The second argument wpse_allowedtags() is a small function that is used to add the tags the_excerpt() will allow. For a complete list of valid HTML5 tags, go and check it out here. Here is function, add any html tag to this that you need to allow/keep

function wpse_allowedtags() {
// Add custom tags to this string
    return '<script>,<style>,<br>,<em>,<i>,<ul>,<ol>,<li>,<a>,<p>,<img>,<video>,<audio>';
}

If you need to allow all HTML tags, that is, no stripping of any tags, the strips_tags() function can be omitted/removed completely.

A point to note however, when html tags are allowed, these tags are counted as words, so your word count for excerpts with tags and without tags will not be the same. To correct that, you will need to remove these tags from the actual word count first so that only words are counted.

I have written an excerpt that will allow all tags, count only words as words, and complete a sentence after the set amount of words (won't trim text mid-sentence) and add a read more text after the last word.

Here is the complete code

function wpse_allowedtags() {
    // Add custom tags to this string
        return '<script>,<style>,<br>,<em>,<i>,<ul>,<ol>,<li>,<a>,<p>,<img>,<video>,<audio>';
    }

if ( ! function_exists( 'wpse_custom_wp_trim_excerpt' ) ) :

    function wpse_custom_wp_trim_excerpt($wpse_excerpt) {
    global $post;
    $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(']]>', ']]&gt;', $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.
                $excerpt_word_count = 75;
                $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
                preg_match_all('/(<[^>]+>|[^<>\s]+)\s*/u', $wpse_excerpt, $tokens);

                foreach ($tokens[0] as $token) {

                    if ($count >= $excerpt_word_count && 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));

                $excerpt_end = ' <a href="'. esc_url( get_permalink() ) . '">' . '&nbsp;&raquo;&nbsp;' . sprintf(__( 'Read more about: %s &nbsp;&raquo;', 'wpse' ), get_the_title()) . '</a>';
                $excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);

                //$pos = strrpos($wpse_excerpt, '</');
                //if ($pos !== false)
                // Inside last HTML tag
                //$wpse_excerpt = substr_replace($wpse_excerpt, $excerpt_end, $pos, 0); /* Add read more next to last word */
                //else
                // After the content
                $wpse_excerpt .= $excerpt_end; /*Add read more in new paragraph */

            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');

You can just remove the '//' from functions that you need extra.

CUSTOM EXCERPT LENGTHS

Sometimes you need to display simple excerpts of different lengths and it is not viable to write an excerpt for every post/function/page. Here is a nice small little function using wp_trim_words

function wpse_custom_excerpts($limit) {
    return wp_trim_words(get_the_excerpt(), $limit, '<a href="'. esc_url( get_permalink() ) . '">' . '&nbsp;&hellip;' . __( 'Read more &nbsp;&raquo;', 'wpse' ) . '</a>');
}

What this little function do is taking get_the_excerpt trimming that to $limit set by the user and returning the text with a read more link at the end.

You can call this excerpt as follow in your template

echo wpse_custom_excerpts($limit);

where $limit will be your word count, so an excerpt of 30 word will be

echo wpse_custom_excerpts(30);

Just one thing to remember here, if you set your limit to more that 55 words, only 55 words will be returned as the excerpt is only 55 words in length. If longer excerpts are needed, use get_the_content instead.

CUSTOM EXCERPT LENGTH

If you just need to alter the length of the_excerpt(), you can use the following function

function wpse_excerpt_length( $length ) {
    return 20;
}
add_filter( 'excerpt_length', 'wpse_excerpt_length', 999 );

Remember, you will need to set a priority bigger than 10 so that your custom function executes after the default.

ADD READ MORE LINK

All text returned by the excerpt have the hated [...] at the end that is not clickable. To add a read more text in the place of the hellips, use this function

 function wpse_excerpt_more( $more ) {
    return ' <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">' . __('Read More', 'your-text-domain') . '</a>';
}
add_filter( 'excerpt_more', 'wpse_excerpt_more' );

EDIT

Excerpt first paragraph

I want to keep this complete, so here is the excerpt that trims after the first paragraph

Here is a function that keeps HTML tags in tact, adds a "Read More" link at the end of the excerpt and trims the excerpt after the first paragraph.

if ( ! function_exists( 'wpse0001_custom_wp_trim_excerpt' ) ) :

function wpse0001_custom_wp_trim_excerpt($wpse0001_excerpt) {
global $post;
$raw_excerpt = $wpse0001_excerpt;
if ( '' == $wpse0001_excerpt ) {

$wpse0001_excerpt = get_the_content('');
$wpse0001_excerpt = strip_shortcodes( $wpse0001_excerpt );
$wpse0001_excerpt = apply_filters('the_content', $wpse0001_excerpt);
$wpse0001_excerpt = substr( $wpse0001_excerpt, 0, strpos( $wpse0001_excerpt, '</p>' ) + 4 );
$wpse0001_excerpt = str_replace(']]>', ']]&gt;', $wpse0001_excerpt);

$excerpt_end = ' <a href="'. esc_url( get_permalink() ) . '">' . '&nbsp;&raquo;&nbsp;' . sprintf(__( 'Read more about: %s &nbsp;&raquo;', 'pietergoosen' ), get_the_title()) . '</a>';
$excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);

//$pos = strrpos($wpse0001_excerpt, '</');
//if ($pos !== false)
// Inside last HTML tag
//$wpse0001_excerpt = substr_replace($wpse0001_excerpt, $excerpt_end, $pos, 0);
//else
// After the content
$wpse0001_excerpt .= $excerpt_end;

return $wpse0001_excerpt;

}
return apply_filters('wpse0001_custom_wp_trim_excerpt', $wpse0001_excerpt, $raw_excerpt);
}

endif;

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'wpse0001_custom_wp_trim_excerpt');

这篇关于如何防止Wordpress在摘录中剥离HTML标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 05:32