我可以在用于创建短代码的函数中返回并包含文件吗? [英] Can I return and include file in a function for creating shortcode?

查看:15
本文介绍了我可以在用于创建短代码的函数中返回并包含文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个将返回一堆 HTML 元素的短代码.一开始这样做很好:

I am creating a shortcode that will return an bunch of HTML elements. In the beginning it was fine to do it this way:

add_shortcode( 'about_us', 'shortcode_about' );
function shortcode_about() {
    return "<div>Some content here.</div>";
}

但是现在我必须添加很多内容,我认为这些内容看起来不太好,因为我的functions.php 将充满很多这样的内容.我想知道我是否可以将它放在一个外部文件中并包含它.

But now I have to add a lot of content, which I think wouldn't look good as my functions.php will be filled with a lot of this. I was wondering if I can just put it in an external file and include it.

我希望这样的事情会奏效:

I hoped something like this would work:

add_shortcode( 'about_us', 'shortcode_about' );
function shortcode_about() {
    return include 'about-us.php';
}

当然,它没有.关于如何正确执行此操作的任何想法?谢谢

But of course, it didn't. Any ideas on how to do this properly? Thanks

推荐答案

add_shortcode( 'about_us', 'shortcode_about' );

function shortcode_about()
{
    // Get absolute path to file.
    $file = locate_template('my-file.php');

    // Check if file is found.
    if ($file) {
        // Return file contents.
        ob_start();
        include $file;
        return ob_get_clean();
    }

    return '';
}

这篇关于我可以在用于创建短代码的函数中返回并包含文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆