0

I am trying to replace a word only on post pages. The issue I am running into is that WordPress page content ends up blank even though this code should only run on post pages.

<?php
/**
* Plugin Name: Wordpress plugin test esmond
* Plugin URI: https://esmondmccain.com
* Description: test plugin.
* Version: 1.0
* Author: Esmond Mccain
* Author URI: https://esmondmccain.com
*/
defined('ABSPATH') or die();

function esmond_enqueue_scripts_styles() {
     if(is_page()){
        //Styles
        wp_enqueue_style( 'bootstrap-css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css');

       //Scripts
       wp_enqueue_script( 'bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js', array('jquery'), true);
     }

}
add_action('wp_enqueue_scripts','esmond_enqueue_scripts_styles');

add_filter('the_content', 'replace_word');
function replace_word($text) {
        if (is_singular( 'post' )){
        $text = str_replace('dog', 'cat', $text);

        return $text;
        }
}

2 Answers 2

1

Your code is returning $text only for posts and nothing for other post types like pages.

Your function should be like this

add_filter('the_content', 'replace_word');
function replace_word($text) {
        if (is_singular( 'post' )){
        $text = str_replace('dog', 'cat', $text);

        return $text;
        }

        // you must return content for pages/ other post types
        return $text;

}
1
  • I can't believe we answered the same way within 15 seconds of each other. That's really funny. Commented Apr 24, 2019 at 13:14
0

You aren't returning $text for any other content. Filters must always return the string whether it's changed or not.

add_filter('the_content', 'replace_word');
function replace_word($text) {
        if (is_singular( 'post' )){
        $text = str_replace('dog', 'cat', $text);

        return $text;
        }
    return $text;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.