【问题标题】:Adding a PHP page to Wordpress via Plugin通过插件将 PHP 页面添加到 Wordpress
【发布时间】:2016-01-22 08:47:58
【问题描述】:

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

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

我从添加重写规则开始

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

那么page.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 注入主题页面的方法。例如生成页面($html);。然后这个方法会去主题的page.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 主题)正在显示这篇文章,然后是数据库中的所有其他文章。我不确定它在哪里或为什么拉所有这些帖子,但如果我能让它停止它看起来这将是一个有效的解决方案。

【问题讨论】:

  • 不明白。你想从你的插件中添加一个模板页面吗?
  • 不完全是,但这就是我想要的最终结果。例如,我希望能够。从我的插件中的 php 脚本生成页面的内容,然后使用当前的主题 page.php 来呈现我的内容。这样它将符合主题 css

标签: php css wordpress


【解决方案1】:

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

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" ) );

希望对您有所帮助。 如果与您的问题不符,请告诉我。

【讨论】:

  • 我需要一个动态系统。我不知道主题路径或模板名称。所以我将只使用默认的 single.php 页面。当我调用 require "...../single.php" 时,它只会加载主页。不知道如何覆盖 $post 对象来做我想做的事。
  • “my_template.php”是插件中的模板页面,如果 is_page() 会覆盖默认模板。如果您想拥有一个动态系统,请删除 if( is_page() ) 并适用于所有情况。
  • 我对我的原始评论添加了一个编辑,以更好地解释我现在的位置。在设置我自己的变量之前,我不确定如何清除默认的 wordpress 变量。当我调用主题 page.php 时,它已经有了一堆东西
猜你喜欢
  • 2016-05-02
  • 2011-02-18
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
相关资源
最近更新 更多