Need help with Shortcode for Trimmed Titles with Permalink
-
By searching through the forums I’ve pieced together a shortcode that truncates titles to a specified character length. I’m making a shortcode so that I can put it in other plugins when I need it and I can adjust the length for each instance. I am counting characters instead of words so that I can insure that the titles don’t wrap to a second line.
Here’s my code:
function short_title( $atts ) { extract( shortcode_atts( array( 'after' => '...', 'length' => '45', ), $atts ) ); //get the post title $title = get_the_title(); // if the title is shorter than the $limit, do nothing if(strlen($title) <= $length) { return $title; } else { $title = substr($title, 0, $length) . $after; return $title; } } add_shortcode('shorter_title', 'short_title');
I then could use the shortcode:
[shorter_title length="30" after="--"]
It works, except I have 2 problems.
1) I think it counts special characters (‘”& etc) different (counting the HTML code). If the trim mark hits a special character, it will show weird characters, like it is showing some of the HTML code for that character. Do you know of a way to eliminate this problem?
2) I would like to have the title link to the post’s permalink. Is there a way to do that by adding code to the function?
I’m not very fluent in PHP, so I apologize if the answers are obvious.
- The topic ‘Need help with Shortcode for Trimmed Titles with Permalink’ is closed to new replies.