我创建了一个插件作为测试,现在遇到了一些麻烦。代码执行了4次,并将echo
在<head>
页面的标记。我执行echo
是因为我在使用另一个插件时遇到了问题,无法理解为什么我的代码被执行了4次。因此,我创建了一个简单的示例,我可以复制并希望能够修复(在您的帮助下)。现在来看看代码。。。
我的职能。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\');
我的包括。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\');
现在,我在网站上有两个页面,一个叫做Test,另一个叫做SubTest。当这些页面中的任何一个是当前页面时$post
对象,我正在输出我的内容,而不是WordPress的$content
. 我已经做了将近3年了,所以如果这些年来我一直做错了,我需要一些指导。生成的html为:
<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
当查看页面的源代码时,这一切都在<head>
. 它还将内容正确地附加到<body>
标签,但另一个在那里,会引起头痛,因为当我POST
, 执行4次。那么,这不是在页面上插入/替换我的内容的正确方法吗?