根据内容长度更改行为

时间:2012-08-17 作者:v3nt

我有大量的帖子,有些只有一句话。这意味着对于某些帖子,所有内容都可以在存档中读取,而无需转到帖子的单个页面。

对于这些帖子,我想禁用帖子标题中的\\u permalink。是否有办法检测摘录长度是否达到限制?

然后我可以用

<a href="<?=($if_has_more_link ? the_permalink() : \'#\' )?>" ><? the_title(); ?></a>

1 个回复
SO网友:fuxia

We need two functions in the theme’s functions.php:

  1. One function checking the length of the content to adjust the title.
  2. Another one to print the formatted post content in case the first function returns TRUE.

Let’s start with the first function. This is rather simple because we solved that already. :)

if ( ! function_exists( \'is_short_content\' ) )
{
    /**
     * Is the passed string not longer than an excerpt?
     *
     * @param  string $content
     * @return boolean
     */
    function is_short_content( $content = NULL )
    {
        NULL === $content && $content = get_the_content();
        // Get maximal excerpt length for this theme
        $max_word_length = apply_filters( \'excerpt_length\', 55 );

        // see \'Counting words in a post\'
        // https://wordpress.stackexchange.com/a/52460/73
        $content_text    = trim( strip_tags( $content ) );
        $content_words   = preg_match_all( \'~\\s+~\', "$content_text ", $m );

        return $content_words <= $max_word_length;
    }
}

The second function will replace the excerpt with the full content conditionally:

if ( ! function_exists( \'t5_show_short_content\' ) )
{
    add_filter( \'the_excerpt\', \'t5_show_short_content\' );

    /**
     * Print the whole content if the visible words are less than the excerpt length.
     *
     * @param  string $excerpt
     * @return string
     */
    function t5_show_short_content( $excerpt )
    {
        $content = apply_filters( \'the_content\', get_the_content() );
        $content = str_replace( \']]>\', \']]&gt;\', $content );
        return is_short_content( $content ) ? $content : $excerpt;
    }
}

Whenever you call the_excerpt() in your theme this function will filter it and return the full formatted content if this is not longer than the excerpt would be.

Now to your initial question: changing the title. We will just reuse the function is_short_content() for that:

if ( is_short_content() )
{
    the_title( \'<h2>\', \'</h2>\' );
}
else
{
    the_title( \'<h2><a href="\' . get_permalink() . \'">\', \'</a></h2>\' );
}

Note how I put the markup into the the_title() function: If a post has no title, we don’t want to see an empty <h2>. And I removed the link completely, because <a href="#"> is a terrible user experience. :)

As a last note: Do not use just <? to open a PHP context. Short open tags are disabled in many environments because they break XML output.

结束

相关推荐

Using the_excerpt() on a page

我一直在尝试利用PHP摘录函数从她最近的博客文章中调用main landing page 无济于事。有什么想法吗?<div id=\"home_news\" class=\"prefix_9 grid_3\"> <div id=\"newsbox\" style=\"display: block;\"> <div id=\"news\"> <h2>Welcome</h2>&#