1

I am new to wordpress and I am trying to display some text on specific pages on my website. My problem is that my plugin replaces my current content on that page with the one on my plugin. How can I make the plugin not replace the content on the page.

add_action( 'the_content', "displayNewsSlider");
function displayNewsSlider(){
  if (is_page('sample-page')){
  echo "plugin content 1";
  echo "plugin content 2";
  }
}
  • 1
    When adding a filter, you must not stop the flow through it, i.e. it must have input and output. Can you spot the missing input and output in your current setup? – birgire Nov 27 '16 at 13:16
  • 1
    the_content is not an action, it's a filter - you need to accept at least one parameter, and always return it afterwards (albeit modified or not). Otherwise as @birgire says, you'll break the flow. – TheDeadMedic Nov 27 '16 at 13:38
  • I changed it to add_filter but it still overwrites my content with the echoes in used in the plugin – iani garthalski Nov 27 '16 at 13:58
3

There is a subtle difference between action hooks and filters. The most notable one is that filter functions are expected to receive a value and pass it along in return when done with their work. Inside the function the value can be modified or be used for something else.

In your case the_content is a filter and on invocation it takes a posts content and sends it as first argument to the first hooked function. The hooked function can now modify this content or for example append something. But the function is also expected to finally return the content string, so it can be passed along to the next function hooked to the hook the_content. This is repeated until all hooked functions are done. Then the end product will be returned to the code which called the filter (this filter is called in the_content(), but it can also be invocated in other places) and only then the resulting string is echoed. That is why it is important to always return the string, else the invocating function doesn't know what to output.

Usage of this filter in you case would look something like this:

add_filter( 'the_content', 'wpse247535_display_news_slider' );
function wpse247535_display_news_slider( $content ) {
    if ( is_page( 'sample-page' ) ) {
        $content .= "plugin content";
        $content .= "more plugin content";
    }
    return $content;
}

So to answer the title of your question: the content of your page is not overwritten, but your function doesn't handle the content string it gets as argument and thus doesn't return it to the invocating function, which then can't output the content anymore, as it got lost on the way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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