定义Wordpress摘录的开头

时间:2013-04-02 18:35:46

标签: wordpress

我正在努力削减我们帖子中的几个字符或文字。我们有关于我们帖子中的故事的日期和来源,但我不喜欢我们摘录中包含的内容和格式,人们坚持认为它必须保留在帖子的顶部。

我如何准确指定我希望摘录在帖子中的开头?我可以从<p>标签开始,或者我可以在开始之前设置要跳过的字符数吗?

非常感谢任何帮助。这是我到目前为止的代码:

<phpcode>
<?php $my_query = new WP_Query('category_name=science&showposts=5'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div id="postlist_container">
<h4 class="und"></h4>
<?php get_the_image(array( 'image_scan' => true , 'image_class' => 'small_image_left','width' => 80 , 'height' => 80)); ?><div class="post_desc"><date><?php the_time('M j, Y') ?></date> &middot; <a href="<?php the_permalink() ?>">
<?php the_title(); ?></a> <br /><br /><?php the_excerpt_max_charlength(250); ?>
</div>
</div>
<div class="clear"></div>
<?php endwhile; ?>
<?php

function the_excerpt_max_charlength($charlength) {
    $excerpt = get_the_excerpt();
    $charlength++;

    if ( mb_strlen( $excerpt ) > $charlength ) {
        $subex = mb_substr( $excerpt, 0, $charlength - 5 );
        $exwords = explode( ' ', $subex );
        $excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
        if ( $excut < 0 ) {
            echo mb_substr( $subex, 0, $excut );
        } else {
            echo $subex;
        }
        echo '[...]';
    } else {
        echo $excerpt;
    }
}
?>
</phpcode>

1 个答案:

答案 0 :(得分:1)

如果日期/来源的长度始终相同(可能不太可能),那么您可以使用substr()上的$excerpt删除X个字符:

// assume we want to remove the first 10 chars
$chars_to_skip = 10;
// get the full excerpt
$excerpt = get_the_excerpt();
// check the length
if ( strlen( $excerpt ) > $chars_to_skip ){
    // remove chars from the beginning of the excerpt
    $excerpt = substr( $excerpt, $chars_to_skip );
}

更有可能的是,您需要进行正则表达式搜索并替换以删除模式匹配的任何内容,即使源文本或日期文本的确切长度在帖子后也不同。您可以使用preg_replace()api info)来完成此操作,但我无法使用正则表达式而不知道您正在使用的格式。