首页 > 解决方案 > 即使定义了 pods(),我也看到错误“调用未定义的函数 pods()”

问题描述

在 WordPress 中,我有两个插件。

第一个插件名为 Pods,它有一个pods()功能。

第二个插件(我创建的)是 Pods 的一个简单插件,它利用了该Pods()功能,如下所示:

<?php

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

//Get the pod for the current post where this shortcode will be appearing
$pod = pods( get_post_type(), get_the_ID() );

//Build the name shortcode
add_shortcode( 'my_name', 'bg_my_name_shortcode' );
function bg_my_name_shortcode($pod) {
    $my_name = $pod->display('my_name');
    return $my_name;
}

但这Uncaught Error: Call to undefined function pods()由于某种原因导致错误,即使pods()在其他 Pods 插件中定义并且它被设计为像这样扩展:https ://pods.io/docs/code/pods/

如果我在函数$pod = pods( get_post_type(), get_the_ID() );内部移动bg_my_name_shortcode它可以正常工作,但是我有很多这些短代码要制作,所以我不想一遍又一遍地调用这三个函数( pods(), get_post_type(), ),而不是调用它一次并将其存储为变量。get_the_ID()

我也很困惑为什么会发生这种情况,因为pods()绝对是 Pods 插件中定义的函数。

标签: phpwordpressundefined

解决方案


您收到该错误的原因是因为尚未加载定义该功能的插件。

您需要在 WordPress 初始化并加载所有插件后声明短代码。试试这个代码:

<?php

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

function bg_my_name_shortcode_init(){
    //Get the pod for the current post where this shortcode will be appearing
    $pod = pods( get_post_type(), get_the_ID() );

    //Build the name shortcode
    add_shortcode( 'my_name', 'bg_my_name_shortcode' );
    function bg_my_name_shortcode($pod) {
        $my_name = $pod->display('my_name');
        return $my_name;
    }
}
add_action('init', 'bg_my_name_shortcode_init');

更多细节可以在这里找到

编辑

修复Uncaught Error: Call to a member function display() on string错误:

<?php

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

function bg_my_name_shortcode_init(){

    function bg_my_name_shortcode() {
        //Get the pod for the current post where this shortcode will be appearing
        $pod = pods( get_post_type(), get_the_ID() );
        $my_name = $pod->display('my_name');
        return $my_name;
    }
    //Build the name shortcode
    add_shortcode( 'my_name', 'bg_my_name_shortcode' );

}
add_action('init', 'bg_my_name_shortcode_init');

推荐阅读