如何从 WordPress 插件中的一个函数调用函数?

How to call function from one function in WordPress plugin?

如何在管理页面中调用插件中的特定功能。 我正在 WordPress 插件中提交表单。提交时,我想检查在表单中输入的密钥的有效性。我有一个检查密钥有效性的函数。我想从表单的函数中调用该函数。 我尝试了一些东西,但它给了我错误 不在对象上下文中时使用 $this

这是我的代码

class WP_Cms_Plugin{

    function __construct() {
        add_action( 'admin_menu', array( $this, 'cms_options_panel' ));
    }

    function cms_options_panel() {
        add_menu_page('CMS', 'Cms', 'manage_options', 'cms-dashboard', array(__CLASS__,'cms_setting_form'), 'dashicons-building');
    }

    function cms_setting_form() 
    {

        if(isset($_POST['btn_submit']))
        {
          $secret_key = $_POST['project_secret_key'];
          if($secret_key=='' || empty($secret_key))
          {
            $error['project_secret_key'] = 'Please enter Secret Key.';
          }
          if(empty($error)){
                call to cms_check_key();
                echo "Key validated successfully";
          } 
          else 
          {
                echo "Please use proper Key";
          }
        }
        ?>
      <form method="post">
            <div>Secret Key</div>
            <input type="text" name="project_secret_key" value="<?php echo esc_attr( get_option('cms_secret_key') ); ?>" required/>
        <?php submit_button('Submit','primary','btn_submit'); ?>
      </form>

        <?php 
    }

    function cms_check_key($secret_key)
    {
        code to check validity
    }
}
$cmsservice = new WP_Cms_Plugin();

问题是您的可调用指定使用 WP_Cms_Plugin class 而不是它的实例(对象)。

将您的 cms_options_panel 函数更改为:

add_menu_page('CMS', 'Cms', 'manage_options', 'cms-dashboard', array($this,'cms_setting_form'), 'dashicons-building');

(将 __CLASS__ 替换为 $this

或者试试静态函数

static function cms_check_key($secret_key)

然后从表单中调用 WP_Cms_Plugin::cms_check_key($secret_key)

PHP Static Keyword