4

I am struggling to get a simple string replace to work in wordpress the_content function.

<?php 

    $phrase = the_content();
    $find = '<p>';
    $replace = '<p style="text-align: left; font-family: Georgia, Times, serif; font-size: 14px; line-height: 22px; color: #1b3d52; font-weight: normal; margin: 15px 0px; font-style: italic;">';

    $newphrase = str_replace($find, $replace, $phrase);

    echo $newphrase;

?>


It just seems to echoing <p> still.

Instead of <p style="text-align: left; font-family: Georgia, Times, serif; font-size: 14px; line-height: 22px; color: #1b3d52; font-weight: normal; margin: 15px 0px; font-style: italic;">

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Joshc
  • 3,825
  • 16
  • 79
  • 121

2 Answers2

7

You need to use apply_filters('the_content') to have Wordpress newlines with paragraphs.

<?php 

    $phrase = get_the_content();
    // This is where wordpress filters the content text and adds paragraphs
    $phrase = apply_filters('the_content', $phrase);
    $replace = '<p style="text-align: left; font-family: Georgia, Times, serif; font-size: 14px; line-height: 22px; color: #1b3d52; font-weight: normal; margin: 15px 0px; font-style: italic;">';

    echo str_replace('<p>', $replace, $phrase);

?>

See the codex entry for the_content. Its in the alternative usage section.

max
  • 96,212
  • 14
  • 104
  • 165
  • I love you man! Can see why it wasn't working now and you've totally fixed. Thank you so much!!!!! – Joshc Nov 15 '12 at 15:21
  • No problem, a lot of the time the Wordpress codex can be either confusing or just wrong and digging into the source helps a lot. – max Nov 29 '12 at 13:41
3

the_content does not return the content but it echoes the content.

If you want to get the content in the variable you have to use

$phrase = get_the_content()

You should run this inside a loop just like the_content()

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Prathik Rajendran M
  • 1,152
  • 8
  • 21
  • Thanks, but if I use `get_the_content()` - it does not output my content in paragraph tags like `the_content()` does. And therefor has nothing to find and replace. – Joshc Nov 15 '12 at 12:37
  • I need to append an inline style to my

    tags.

    – Joshc Nov 15 '12 at 13:04
  • Yes, but Prathik is right; if you use the_content(), you are not placing the content value in $phrase, you are actually directly echoing it. Anyway, your solution is to use apply_filters() as mentioned by papirtiger – barakadam Nov 15 '12 at 14:02