The other day I was trying to write a short-code function for a WordPress 3.2.1 blog, by which I could enable authors to insert html span tags into post titles in single post view (i.e., insertion inside the HTML output), so as to be able to control and style certain words or groups of words within titles through CSS classes. My idea was to:
- Trigger the insertion through a short-code to insert the html-rich version of the title;
- Launch a pregmatch to replace the old title with its new version.
For some reason I got stuck in step 1, in the str_replace part of the function. Even though I decided to go with a different approach (using custom fields), I am still curious as to why my approach didn't work. I'm really at a beginner level when it comes to php, so I could really use the feedback on this function. Thanks in advance!
<?php
function userf_html_titles( $atts ) {
extract( shortcode_atts( array(
'highlight' => '',
), $atts ) );
$title = the_title('', '', false);
$title_array = explode (' ',$title);
$input_array = explode (",", $highlight);
foreach ($input_array as $input_value) {
if ($input_value == null) {
$title_sub = $title_array;
} else {
if ( strpos($title,$input_value) === false ) {
$title_sub = $title_array;
} else {
$new_title = $title_array;
str_replace (
array (
$input_array[0],
$input_array[1],
$input_array[2],
$input_array[3],
),
array (
'<span style="color:#d00;">'.$input_array[0].'</span>',
'<span style="color:#d00;">'.$input_array[1].'</span>',
'<span style="color:#d00">'.$input_array[2].'</span>',
'<span style="color:#d00">'.$input_array[3].'</span>',
),
$new_title);
$title_sub = $new_title;
}
}
$title_return = implode(' ',$title_sub);
}
return '<h1>'.$title_return.'<h1>';
}
add_shortcode( 'title', 'userf_html_titles' );
?>