从 functions.php 简码调用 class 函数

Calling a class function from functions.php shortcode

我认为这毫无疑问会起作用,但我遗漏了一些东西。

在我的 wordpress 中 child functions.php:

function HelloWorldShortcode() {
    return My_Custom_Plugin_Public::display_custom_block();
}
add_shortcode('helloworld', 'HelloWorldShortcode');

display_custom_block() 函数:

    public static function display_custom_block() {
echo "hello world hello world";
    }

很遗憾,页面无法加载此短代码。我不能从短代码中调用 class 函数吗?

整个class:

<?php

defined( 'ABSPATH' ) or die();
class My_Custom_Plugin_Public {

    private $plugin_name;

    private $version;

    public function __construct( $plugin_name, $version ) {

        $this->plugin_name = $plugin_name;
        $this->version = $version;

    }

    public static function display_custom_block() {
echo "hello world hello world";
    }
}

首先将 class 文件导入到 functions.php,如您所说,它是自定义的

require_once( __DIR__ . '/YourCustomClass.php'); //Path of file

然后在你的函数中你可以这样调用

function HelloWorldShortcode() {
    return My_Custom_Plugin_Public::display_custom_block();
} 
add_shortcode('helloworld', 'HelloWorldShortcode');

这应该有效