is it possible to show only the first line of content <?php the_content(); ?>
or alternative only content between <b>text</b>
?
3 Answers
you could also do something like:
function rt_before_after($content) {
$replace = "</b>";
$shortcontent = strstr($content, $replace, true).$replace;
if ($shortcontent === false) $shortcontent = $content;
return $shortcontent;
}
add_filter('the_content', 'rt_before_after');
It should look for the first </b>
in your content and return everything before that. it then adds the </b>
back. The function takes that string and replaces your content.
-
-
did you add the if statement? what is the error on your site?– rudtekCommented Nov 21, 2018 at 17:31
-
the site is empty after the code. Maybe I made a mistake. Your code belong in the function file right? how do I show the shortcontent? Still with '<?php the_content(); ?>'?– joloshopCommented Nov 21, 2018 at 17:42
-
Yes in functions file. I added error check above. looks like it doesn't like html codes. It works if you add a word that is actually in the page, but not with html. Sorry– rudtekCommented Nov 21, 2018 at 17:50
-
What you can do is work with this the_excerpt()
change this instead of the_content();
And give the amount of words that you want, add this in functions.php after you add the_excerpt();
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
More info here: https://developer.wordpress.org/reference/functions/the_excerpt/
After that force the first line, using this for example.
.post p {
width: 100px;
white-space:nowrap;
overflow:hidden;
}
add the width of the content.(even if its responsive just change the css as you want).
-
Thanks, I know that however ist not about the amount of words its about the first line (sometimes these line has only 2 Words sometimes 10)– joloshopCommented Nov 21, 2018 at 17:21
-
Thanks again, however even if its works partial it still shows the content only hidden and therefore visible for search engines ;-)– joloshopCommented Nov 21, 2018 at 17:40
-
Found a solution! I use this code:
function awesome_excerpt($text, $raw_excerpt) {
if( ! $raw_excerpt ) {
$content = apply_filters( 'the_content', get_the_content() );
$text = substr( $content, 0, strpos( $content, '</p>' ) + 4 );
}
return $text;
}
add_filter( 'wp_trim_excerpt', 'awesome_excerpt', 10, 2 );
and than use <?php the_excerpt(); ?>