Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

wordpress - How to trim WP category title using functions.php

I am fairly new to WP functions so hoping someone could shed some light on this issue. I have a function that displays five posts from a specific category, then using a shortcode to display the results on certain WP posts/pages. I am having trouble to include wp_trim_words to get_the_title(). I want to limit the title to 5 words and end with "...". I saw many examples in here but none that would fit into my function. Can anyone help please?

function wpb_postsbycategory() {
// the query
$the_query = new WP_Query( array( 'category_name' => '3dgames', 'posts_per_page' => 5 ) ); 
 
// The Loop
if ( $the_query->have_posts() ) {
    $string .= '<ul class="postsbycategory widget_recent_entries">';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
            if ( has_post_thumbnail() ) {
            $string .= '<p><a href="' . get_the_permalink() .'" style="color:#FFF;" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 100, 50) ) . get_the_title() .'</a><br></p>';
            } else { 
            // if no featured image is found
            $string .= '<li><a href="' . get_the_permalink() .'" style="color:#FFF;" rel="bookmark">' . get_the_title() .'</a></li>';
            }
            }
    } else {
    // no posts found
}
$string .= '</ul>';
 
return $string;
 
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('3dgames', 'wpb_postsbycategory');
 
// Enable shortcodes in text widgets
add_filter('widget_text', 'do_shortcode');
question from:https://stackoverflow.com/questions/65886573/how-to-trim-wp-category-title-using-functions-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use wp_trim_words() and inside place the title for the post: wp_trim_words(get_the_title(), 5, '...')

In your case it should be something like this:

if ( has_post_thumbnail() ) {
    $string .= '<p><a href="' . get_the_permalink() .'" style="color:#FFF;" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 100, 50) ) . (wp_trim_words(get_the_title(), 5, '...')) .'</a><br></p>';
} else { 
    // if no featured image is found
    $string .= '<li><a href="' . get_the_permalink() .'" style="color:#FFF;" rel="bookmark">' . (wp_trim_words(get_the_title(), 5, '...')) .'</a></li>';
}

For more details on how wp_trim_words() works you could visit the official documentation: https://developer.wordpress.org/reference/functions/wp_trim_words/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...