通过插件将PHP页面添加到Wordpress


Adding a PHP page to Wordpress via Plugin

几乎所有

我遇到的将php页面添加到Wordpress的指南都涉及在主题级别添加它。 例如,如何将PHP页面添加到WordPress?我想通过插件向多个站点添加新的面向公众的页面。我不想把它添加到几十个主题中。如果我可以在插件级别添加它,它将适用于所有站点。

我有这个工作,但我需要某种方式将其注入主题。为了获取侧边栏和东西,而无需为每个主题添加自定义css。

我从添加重写规则开始

RewriteRule ^mypage /wp-content/plugins/myplugin/mypage.php [QSA,L]

然后页面.php包含

require_once('../../../wp-blog-header.php');
get_header();
//custom php content
//get_sidebar(); // how to get this working.
get_footer();

这也有效,但我遇到的问题是侧边栏。有些主题没有它们,而另一些主题有。并非所有侧边栏都是 30% 等。我不知道如何在这里构建div 结构以使其工作。某些主题的页面宽度为 100%,但在固定宽度的其他主题上查看时,这看起来很丑陋。我已经能够提出一些妥协,但我宁愿能够做到这一点。

在夏天,我的主要问题是。是否可以调用将 html 注入主题页面的方法。例如generate_page($html);。然后,此方法将转到主题的页面.php并将$html注入主题的内容区域。

编辑为了尝试将内容动态注入未知主题,我做了以下工作

global $post;
$post->post_content = "TEST PAGE content";
$post->post_title = "Page Title";
$post->post_name = "test-page";
include get_template_directory()."/page.php";

这适用于某些主题,而不适用于其他主题。一些主题可以很好地显示这篇文章,但其他主题(默认的wordpres 25 15主题)显示这篇文章,然后在它之后显示数据库中的所有其他帖子。我不确定它在哪里或为什么拉动所有这些帖子,但如果我可以让它停止,看起来这将是一个有效的解决方案。

然后,您可以尝试在特定情况下加载特定的模板页面。

function load_my_template( $template )
{
    if( is_page() )
        $template = plugin_dir_path(__FILE__) . "dir_to/my_template.php";
    return $template;
}

或更改加载页面上使用的内容

function load_my_content( $content )
{
    global $post;
    $id = $post->ID;
    if( is_page() )
    {
        ob_start();
        include plugin_dir_path(__FILE__) . "dir_to/my_template.php";
        $content = ob_get_clean();
    }
    return $content;
}

在你的__construct()

add_filter('template_include', array($this,'load_my_template') );
add_filter("the_content", array($this,"load_my_content" ) );
add_filter("get_the_content", array($this,"load_my_content" ) );

希望对您有所帮助。告诉我它是否与您的问题不符。