How to display only specific part of the_content()

2019-06-12 21:51发布

Is there any way how to trim content and only display text within h2 tags in wordpress?

I am trying to display only a specific part of post content on my specific page not the whole of it. The excerpt does not work in this case as it is only defined by the length. I bet there is a simple way to do it... just cannot find one yet.....

thank you all.....

1条回答
戒情不戒烟
2楼-- · 2019-06-12 22:57

This can be made in several ways, but the easiest would be :

function o99_filter_the_content_h2( $content ) {


 $pattern = "/<h2>(.*?)<\/h2>/";
    preg_match($pattern, $content, $matches);
    return $matches[1];
}

add_filter( 'the_content','o99_filter_the_content' );

add it to your functions.php file in your theme.

Note that it will no longer be h2 :-)

IF you would like to use the same for any other tag , you can use a more generic function:

 function o99_filter_tags_generic($content, $tagname)
 {
    $pattern = "/<$tagname>(.*?)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
 }

where $tagname is the tag to filter

查看更多
登录 后发表回答