How to get and display only the first paragraph of a category description

[ad_1]

With this you can determine the 1st paragraph from a string:

$string = substr($string, strpos($string, "<p"), strpos($string, "</p>")+4);

The challenge now, however, is that you’re dealing with category text. I don’t know in what context you are accessing these. Here’s a minimal example of how to load the description text from a given category and get the 1st paragraph from it and output it:

$term = get_term_by('term_id', 1, 'category');
$string = wp_kses_post( wpautop($term->description) );
$string = substr($string, strpos($string, "<p"), strpos($string, "</p>")+4);

Thread Starter
gunkev

(@gunkev)

This is how I am getting the cat description

$term = get_queried_object();
<?php echo  mb_strimwidth($term->description, 0, 310, "...") ?>

Please the +4 value represent ? the number of characters ?

Thread Starter
gunkev

(@gunkev)

I just tested you method but I am still getting the same results. The value at the send seems to precise the number of characters.

Your code returns a string that does not contain HTML code for paragraphs. Therefore my tip does not work like this. With your code you would have to use strpos() to find the position of line breaks. This is possible, but imho difficult.

$term = get_queried_object();
    $string = mb_strimwidth( $term->description, 0, 310, "..." );
    $string = wp_kses_post( wpautop($string) );
    $string = substr($string, strpos($string, "<p"), strpos($string, "</p>")+4);
    echo wp_strip_all_tags($string);

Output is then:

<p>my paragraph.</p>

If you don’t want HTML code, wrap the output with:

echo wp_strip_all_tags($string);

Thread Starter
gunkev

(@gunkev)

Thanks @threadi it’s working well

  • This reply was modified 8 minutes ago by gunkev.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer