WordPress:只回显帖子标题的前60个字符

时间:2017-03-08 14:49:27

标签: php wordpress if-statement ternary-operator

我正在构建一个WordPress主题,我想确保如果帖子标题超过60个字符,它会显示前6个字符+ 最后三点(...)

Native Php希望:

<?php    
     if (strlen($title) <= 60) {
        echo %title
     }  else {
        echo (substr($title, 60) . "..."
     }                          
?>  

我的问题是,在WordPress中,变量的语法不是 $ title ,而是%title ,正如您在代码中看到的那样:

<?php previous_post_link( '%link', '%title ' ); ?>

我的问题是:

  1. 如何成为WordPress中的最终IF
  2. if / else(三元)形式如何简写?
  3. 由于

1 个答案:

答案 0 :(得分:1)

您可以通过创建自定义post_nav函数来实现此目的

<div class="prev-posts pull-left">
    <?php
    $prev_post = get_previous_post();
    if ($prev_post)
    {
        $prev_title = strip_tags(str_replace('"', '', $prev_post->post_title));
        if (strlen($prev_title) >= 60)  //<-- here is your custom checking
        {
            $prev_title = (substr($prev_title, 0, 60)) . "...";
        }
        echo "\t" . '<a rel="prev" href="' . get_permalink($prev_post->ID) . '" title="' . $prev_title . '" class=" "><strong><<< &quot;' . $prev_title . '&quot;</strong></a>' . "\n";
    }

    ?>
</div>
<div class="next-posts pull-right">
    <?php
    $next_post = get_next_post();
    if ($next_post)
    {
        $next_title = strip_tags(str_replace('"', '', $next_post->post_title));
        if (strlen($next_title) >= 60) //<-- here is your custom checking
        {
            $next_title = (substr($next_title, 0, 60)) . "...";
        }
        echo "\t" . '<a rel="next" href="' . get_permalink($next_post->ID) . '" title="' . $next_title . '" class=" "><strong>&quot;' . $next_title . '&quot; >>></strong></a>' . "\n";
    }

    ?>
</div>

希望这有帮助!