I have a plugin I created as a test and am running into a bit of trouble. The code is executing 4 times and placing what I echo
in the <head>
tag of the page. The reason I'm performing an echo
is that I am having trouble with another plugin and cannot figure out why my code was being executed 4 times. So, I created a simple example that I can replicate and hopefully fix (with your help). Now onto the code...
My functions.php:
/*
Plugin Name: What Have I Done?
Plugin URI: http://www.myplugintest4times.com
Description: This is just a test for replicated html in the head.
Version: 1.0.0
Author: Someone Special
Author URI: http://www.somewhereoutthere.com
*/
// Definitions
define('MY_PLUGIN_PATH' , plugin_dir_path( __FILE__ ));
define('MY_PLUGIN_URL', get_option('siteurl') . '/wp-content/plugins/testplugin');
// Classes
require_once(dirname(__FILE__) . '/includes.php');
My includes.php:
function mytest_filter($content) {
global $post;
echo "<p>my test again</p>";
$testpage = get_page_by_title('Test');
$subtestpage = get_page_by_title('SubTest');
if ($post->ID == $testpage->ID || wp_get_post_parent_id($subtestpage) == $testpage->ID) { // this is a test page, filter the content...
switch($post->ID) {
case $testpage->ID:
echo "this is the test page"; // return $html;
break;
case $subtestpage->ID:
echo "this is the sub test page (test is the parent)"; // return $html;
break;
}
}
else {
return $content;
}
}
add_filter('the_content', 'mytest_filter');
Now, I have two pages on the site, one called Test and one called SubTest. When either of those pages are the current $post
object, I am outputting my content instead of WordPress's $content
. I've been doing this for almost 3 years now, so if I've been doing it wrong all these years, I need some direction.
The resulting html is:
<p>my test again</p>
this is the test page
<p>my test again</p>
this is the test page
<p>my test again</p>
this is the test page
<p>my test again</p>
this is the test page
And when viewing source for the page, this is all in the <head>
. It also appends the content properly in the <body>
tag, but the other is there and is causing headaches because when I peform a POST
, it gets executed 4 times. So, is this not the proper way to inject/replace my content on a page?