【问题标题】:Combining a PHP template with a shortcode将 PHP 模板与简码相结合
【发布时间】:2018-06-25 14:06:24
【问题描述】:

我使用的页面构建器不允许我插入 PHP 代码(仅限 HTML)。但它会接受简码。

由于我想包含一个完整的自定义帖子类型区域,我正在尝试将自定义帖子类型循环添加到一个单独的文件中,并使用短代码来显示此文件中的代码。我要包含的文件称为 team.php 并且从目录中位于 /inc/team.php

我在另一篇文章中找到了此代码 sn-p 以添加到我的函数文件中,并且我添加了我的文件名并根据注释说明调整了文件目录。

add_shortcode('include', 'include_php_file');
function include_php_file($atts=array(), $content='') {
    $atts = shortcode_atts(array(
        'file' => ''
    ), $atts);
    if(!$atts['file']) return 'team.php'; // needs a file name!
    $file_path = dirname(__FILE__).'/inc/'.$atts['file']; // adjust your path here
    if(!file_exists($file_path)) return '';
    ob_start();
    include($file_path);
    $html = ob_get_contents();
    ob_end_clean();
    return $html;
}

制作简码:[include file='team.php'](我想!)...

我希望这是解决方案,但它似乎没有在我的 team.php 文件中输出代码。

我确定我在这里遗漏了一些简单的东西,但我似乎看不出哪里出错了。任何帮助将不胜感激!

【问题讨论】:

  • 你试过调试你的代码吗?评估 file_exists($file_path) 代码 sn-p 是什么?
  • 另外,return team.php退出函数,而不是继续使用该文件名。那行应该是if(!$atts['file']) { $atts['file'] = 'team.php';}
  • 另外,我强烈建议不要使用这种编码风格。相反,我会在您的主题中编写一个呈现自定义帖子类型的函数,并在此短代码中调用该函数
  • 感谢换行,Cale_b - 它似乎没有解决任何问题 - 早上我会尝试用新的眼睛看它......关于呈现 CPT 的功能 - 我不知道甚至不知道从哪里开始!!你能举出任何例子吗?

标签: php wordpress shortcode wordpress-shortcode


【解决方案1】:

好的,我找到答案是下面的代码:

function get_team($atts) {
  ob_start();
  get_template_part('/inc/team');
  return ob_get_clean();
}
add_shortcode('display-team', 'get_team');

到目前为止,对我来说效果很好,除非有人有更好的解决方案?

【讨论】:

    猜你喜欢
    • 2020-03-30
    • 1970-01-01
    • 2016-04-29
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多