【问题标题】:Inserting a php file into a Wordpress shortcode将 php 文件插入 Wordpress 短代码
【发布时间】:2016-06-08 17:53:09
【问题描述】:

我制作了一个海关脚本,用于根据用户的来源输出某个电话号码。我已经能够使用以下简单的 sn-p 在网站的标题中进行设置:

<?php include 'TelephoneNumber.php';?>

我现在需要创建一个简码,以便我可以在 Wordpress 测试编辑器中调用它。我创建了一个非常简单的短代码,但我无法弄清楚如何包含上面的文件名。

custom_shortcodes.php(放在 wp-content 文件夹中)

<?php
function telephone_number(){
return 'PHONE NUMBER HERE';
} // End telephone_number()
?>

function.php(主题)

include(WP_CONTENT_DIR . '/custom_shortcodes.php');
add_shortcode( 'telephone_number_sc', 'telephone_number' );

简码会在此处输出文本 PHONE NUMBER。但是,这没用,因为它没有调用我需要的脚本。

如何使用包含文件功能?

【问题讨论】:

    标签: php wordpress shortcode


    【解决方案1】:

    您可以将函数与短代码放在同一个文件中,也可以将它们放在单独的文件中,但它们需要正确构造。 include 的工作方式与 require 相同,我只是更喜欢 require。

    在同一个文件中

    在functions.php中

    您需要/包含短代码文件:

    require('custom_shortcodes.php');
    

    在 custom_shortcodes.php 中

    // phone number function
    function telephone_number(){
            return 'PHONE NUMBER HERE';
    } // End telephone_number()
    

    要制作简码,您需要遵循特定的方式:

    //shortcode
    function output_shorcode($atts, $content = null){
         $number = telephone_number();
         return $number;
    }
    add_shortcode( 'number', 'output_shortcode' );
    

    然后将 [number] 放在需要号码的地方

    在单独的文件中

    在functions.php中

    您需要/包含短代码文件和数字文件:

    require('phone_number.php');
    require('custom_shortcodes.php');
    

    在 custom_shortcodes.php 中

    function output_shorcode($atts, $content = null){
             $number = telephone_number();
             return $number;
        }
        add_shortcode( 'number', 'output_shortcode' );
    

    在 phone_number.php 中

    // phone number function
        function telephone_number(){
                return 'PHONE NUMBER HERE';
        } // End telephone_number()
    

    【讨论】:

    • 嗨凯拉,感谢您的回复! 'PHONE NUMBER HERE' 我想删除它并尝试包含 TelephoneNumber.php 文件,因为它包含许多其他代码来显示某个号码,具体取决于它们来自哪里等。这仍然是正确的方法吗它?我只需将 放在 php 文件中,我的脚本就可以工作,但我无法将 PHP 添加到 wordpress HTML 文本编辑器中,所以我认为使用短代码是最好的方法。非常感谢
    • 嗨,亚历克斯,不客气。我将在telephoneNumber.php 文件中有一个主电话号码函数,它结合了所有其他函数并输出它,并让简码返回该函数。简码是始终如一地在所需位置输出写入编号的最佳方式。
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2017-07-25
    • 2018-06-04
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    相关资源
    最近更新 更多