【问题标题】:change wordpress excerpt length depending on post class根据帖子类别更改wordpress摘录长度
【发布时间】:2014-07-31 08:26:42
【问题描述】:

我在 WordPress 中使用以下 PHP 将不同的类应用于我主页上的帖子,具体取决于它们的位置:

<article id="post-<?php the_ID(); ?>"
<?php 
    $extra = ( ( $wp_query->current_post % 5 == 0 && !is_page() ) ? 'full' : 'half' ) . ( ( ( $wp_query->current_post % 5 == 1 || $wp_query->current_post % 5 == 3 ) && !is_page() ) ? ' left' : '' );
    post_class($extra);
?>>

在我的functions.php中,我使用以下内容来更改这些帖子的摘录长度:

function twentytwelvechild_custom_excerpt_length( $length ) {
    global $wp_query;
    if( $wp_query->current_post%5 == 0 ) return 30;
    else return 12;
}
add_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_length', 12 );`

这使得每 5 个帖子的第一个帖子的摘录长度为 30,其余 12 个,但我不想这样做。

如何使用 PHP 将 'full' 类的文章的摘录长度更改为 30 个单词,将半个类的文章的摘录长度更改为 12 个单词?

希望这是有道理的

詹姆斯

【问题讨论】:

  • php是什么意思?期望的输出是什么?请准确。你的问题没有意义

标签: wordpress


【解决方案1】:

我已经解决了!!基本上,我上面使用的 PHP 对每个帖子页面都有影响——档案、博客页面、搜索结果。我问这个问题是因为我正在设计我的搜索页面并且希望搜索结果看起来与存档和主页布局不同。所以我只是把上面的条件设为“更有条件”

function twentytwelvechild_custom_excerpt_length( $length ) {
    global $wp_query;
    if( $wp_query->current_post%5 == 0 && ( is_home() || is_archive() ) )
        return 30;
    else return 12;
}
add_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_length', 12 );

【讨论】:

    【解决方案2】:

    选项 1:

    使用摘录长度过滤器将它们全部设为 30,然后使用 wp_trim_words() 在页面本身上删除一些内容。

    选项 2:

    从您的原始过滤器挂钩中删除条件并返回 30。创建一个将返回 12 但实际上不挂钩它的新函数。

    function twentytwelvechild_custom_excerpt_length( $length ) {
        return 30;
    }
    add_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_length', 12 );
    
    function twentytwelvechild_custom_excerpt_short( $length ) {
        return 12;
    } 
    

    然后,当您想显示较短的摘录时,请在页面上使用以下内容。

    add_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_short', 20 );
    the_excerpt();
    remove_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_short', 20 );
    

    通过在输出摘录之前添加过滤器,您将长度更改为 12。您正在显示摘录然后删除过滤器,因此任何后续帖子都将恢复到正常的 30。

    【讨论】:

    • 感谢您如此迅速地回复我,内森。我将如何在具有“.half”类的帖子上使用 wp_trim_words()?
    • 我已经解决了!!基本上,我上面使用的 PHP 对每个帖子页面都有影响——档案、博客页面、搜索结果。我问这个问题是因为我正在设计我的搜索页面并且希望搜索结果看起来与存档和主页布局不同。所以我只是把上面的条件'更多条件'function twentytwelvechild_custom_excerpt_length( $length ) { global $wp_query; if( $wp_query-&gt;current_post%5 == 0 &amp;&amp; ( is_home() || is_archive() ) ) return 30; else return 12; } add_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_length', 12 );
    • @JamesWaterhouse 你应该添加你的评论作为答案
    猜你喜欢
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    相关资源
    最近更新 更多