我想限制我的post_excerpt长度15,这里是:
function expert_shortcode($atts){
extract( shortcode_atts( array('title' => '','category' => ''), $atts, 'expert' ) );
$q = new WP_Query(
array('category_name' => $category, 'posts_per_page' => '5', 'post_type' => 'post')
);
$list = '<div class="left_top"><h3 class="left_top_title"> '.$title.'</h3>';
while($q->have_posts()) : $q->the_post();
//get the ID of your post in the loop
$id = get_the_ID();
$post_excerpt = get_post_meta($id, 'post_excerpt', true);
$post_thumbnail=get_the_post_thumbnail( $post->ID, 'thumbnail');
$list .= '
<div class="left_top ">
'.$post_thumbnail.'
<h3><a href="'.get_permalink().'">'.get_the_title().'</a></h3>
<p>'.$post_excerpt.'</p>
</div>
';
endwhile;
$list.= '</div>';
wp_reset_query();
return $list;
}
add_shortcode('expert', 'expert_shortcode');
它使用自定义字段输入,但我希望限制字长15。
答案 0 :(得分:3)
因为,您使用的是自定义字段,我们必须编写自己的函数。无论如何,PHP非常酷,并给我们explode
。以下是我们将如何做到这一点:
function custom_excerpt( $excerpt ) {
$parts = explode( $excerpt, ' ', 15 ); // explode string after 15 spaces
return $parts[0]; // taking the first part of the array
}
如果您使用the_excerpt
,则可以编写一个过滤器来控制长度:
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
答案 1 :(得分:0)
你可以尝试下面的代码
substr($post_excerpt, 0, 15);
限制词语
$words = explode(' ', $post_excerpt);
echo implode(' ', array_slice($words, 0, 15));
您的代码就像
add_filter('pre_get_posts', 'set_post_order_in_admin' );
function expert_shortcode($atts){
extract( shortcode_atts( array('title' => '','category' => ''), $atts, 'expert' ) );
$q = new WP_Query(
array('category_name' => $category, 'posts_per_page' => '5', 'post_type' => 'post')
);
$list = '<div class="left_top"><h3 class="left_top_title"> '.$title.'</h3>';
while($q->have_posts()) : $q->the_post();
//get the ID of your post in the loop
$id = get_the_ID();
$post_excerpt = get_post_meta($id, 'post_excerpt', true);
$words = explode(' ', $post_excerpt);
$data=implode(' ', array_slice($words, 0, 15));
$post_thumbnail=get_the_post_thumbnail( $post->ID, 'thumbnail');
$list .= '
<div class="left_top ">
'.$post_thumbnail.'
<h3><a href="'.get_permalink().'">'.get_the_title().'</a></h3>
<p>'.$data.'</p>
</div>
';
endwhile;
$list.= '</div>';
wp_reset_query();
return $list;
}
add_shortcode('', 'expert_shortcode');