WordPress – Search and replace on a post content at view time

I have a plugin that was not created by me, that grabs web content from the web and displays inside a wordpress post.

The problem is that the app description shows the text with no <br >. The plugin converts everything to n.

Read More

I had an idea of building a one line plugin to intercept the post being written at view time and replacing n with <br />.

I have never created a plugin for wordpress. Reading the web I come out with this:

<?php 
    /*
    Plugin Name: Convert n in HTML BR
    Plugin URI: 
    Description: Convert n in HTML BR
    Author: Me
    Version: 1.0
    Author URI: 
    */

function my_function($id) {
  $the_post = get_post($id);
  $content = str_replace("n", "<br />", $the_post->post_content);
  return $content;
}
add_action('the_post', 'my_function');

?>

But this has no effect.

I have also tried this:

add_filter('the_content', 'modify_content');
function modify_content($content) {
    global $post;
    if ($post->ID != $desired_id)
        return $content;

    $modified_content = str_replace("n", "<br />", $the_post->post_content);
    return $modified_content;
}

What is wrong? I am basically following a recipe from a post on the web.

Related posts

2 comments

  1. I’d try making your change directly to the post object:

    add_action( 'the_post', 'replace_newline' );
    
    function replace_newline( $post ) {
        $post->content = str_replace( "n", "<br>", $post->post_content );
    }
    
  2. Using a filter on the_content object you can replace any HTML string on the fly using this code:

    function replace_text($text) {
        $text = str_replace('look-for-this-string', 'replace-with-this-string', $text);
        $text = str_replace('n', '<br>', $text);
        return $text;
    }
    add_filter('the_content', 'replace_text');
    

Comments are closed.