我如何在我的WordPress主题中限制上一篇/下一篇文章的长度?

时间:2016-05-23 作者:Benedikt W

我正在使用以下代码显示wordpress主题中的下一篇/上一篇文章。

<?php
previous_post_link(\'<span class="left">&larr; %link</span>\');
next_post_link(\'<span class="right">%link &rarr;</span>\'); ?> 
这是可行的,但我想将链接中显示的帖子标题限制在特定的长度,因为太大的链接因为我的空间太大而不起作用。我想把箭头放在链接中,这样它就能以相同的样式显示链接和箭头。这也可能吗?

非常感谢。

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

这里有一个小的代码可以为您实现这一点:

<?php $max_length = 5; // set max character length here

$next = get_next_post()->ID;
$prev = get_previous_post()->ID;

if( $prev ) {
    $title = get_the_title( $prev );
    $link = get_the_permalink( $prev );
    $post_name = mb_strlen( $title ) > $max_length ? mb_substr( $title, 0, $max_length ) . \' ..\' : $title;
    ?>
        <span class="left">
            <a href="<?php echo $link; ?>" rel="prev" title="<?php echo $title; ?>">&larr; <?php echo $post_name; ?></a>
        </span>
    <?php
}
if( $next ) {
    $title = get_the_title( $next );
    $link = get_the_permalink( $next );
    $post_name = mb_strlen( $title ) > $max_length ? mb_substr( $title, 0, $max_length ) . \' ..\' : $title;
    ?>
        <span class="right">
            <a href="<?php echo $link; ?>" rel="next" title="<?php echo $title; ?>"><?php echo $post_name; ?> &rarr;</a>
        </span>
    <?php
} ?>
希望这对你的模板有帮助。

编辑:较小的修复,因此可以处理多字节字符。(mb\\U strlen-mb\\U substr)

SO网友:Antony Gibbs

这可以通过使用基于最大宽度和文本溢出属性的简单css来实现。

<style>
    /**
     * note that your theme might not use class nav_posts
     * so you might have to adjust to your need
     */

    .nav_posts .title {
        /**
         * This is what is minimum required for the magic
         * First it has to be a block... inline blocks are cool and simple to use,
         * but if your theme used blocks (includes flex) don\'t upset him and take that line out
         */
        display: inline-block;

        text-overflow: ellipsis;

        /* Required for text-overflow to do anything */
        overflow: hidden;
        white-space: nowrap; /* forces text to fit on one line */

        max-width: 30ex; /* Fit to your needs... */

        /* Then what ever you need to fit in your theme */
        vertical-align: bottom;
    }
</style>

<!--
// Check out your theme (could be in single.php)
// the below php is only to illustrate the case.
// Make your life simple, don\'t edit the theme or any php, adjust the css
// adding it using wordpress custom css, nothing more, as simple as that :)
-->

<?php

previous_post_link(\'<span class="nav_posts left">&larr; <span class="title">%link</span></span>\');

next_post_link(\'<span class="nav_posts right"><span class="title">%link</span> &rarr;</span>\');

?>

SO网友:Rarst

这两个问题都应该逐步解决get_adjacent_post_link() 函数,它通过动态{$adjacent}_post_link 过滤器(其中$adjacentpreviousnext).

您应该能够使用此过滤器对最终输出进行任何更改。