Wordpress:从主题访问插件的功能

Lee*_*ald 8 wordpress plugins themes wordpress-plugin

我正在尝试从我已经制作成Wordpress主题的插件中添加一些功能,但我没有什么快乐.文档并没有真正帮助我解决问题,所以也许这里的人可以提供帮助.

我在Wordpress中有一个插件,它被激活并正常工作.这个插件的类有一个名为generateHtml的函数,我想从Wordpress主题访问它.但无论我尝试什么,我似乎无法访问我的插件的代码.

可以向我总结一下我需要做些什么才能让主题从插件中访问代码和/或指出我在我的代码中出错了:

插入:

<?php
/** Usual comments here **/

if (!class_exists("ImageRotator")) {
  class ImageRotator {
    private $uploadPath = '';
    private $pluginPath = '';
    private $options;

    function __construct() {
      $this->uploadPath = dirname(__file__).'\\uploads\\';
      // add_shortcode('imagerotator', array(&$this, 'generateHtml'));
    }

    // Various functions for plugin

    function generateHtml() {
      echo '<p>Hello World</p>';
    }
  }
}

/**
 * Create instance of image rotator
 */
$imageRotator = new ImageRotator();

/**
 * Create actions & filters for Wordpress
 */
if (isset($imageRotator)) {
  // Actions
  add_action('admin_menu', array(&$imageRotator, 'createMenu'));
  add_action('admin_init', array(&$imageRotator, 'registerSettings'));
  add_action('imagerotator_show', array(&$imageRotator, 'generateHtml'));
}
Run Code Online (Sandbox Code Playgroud)

主题标题页中的部分:

<?php if (isset($imageRotator)) {
        $imageRotator->generateHtml();
    } else if (isset($ImageRotator)) {
        print_r($ImageRotator);
    } else {
        echo '<p>Nope!</p>';
    }

    if (function_exists("imagerotator_show")) {
      echo 'Function found';
    } else {
      echo 'Function NOT found';
    }
?>
Run Code Online (Sandbox Code Playgroud)

目前我所看到的只是"Nope"和"找不到功能".感谢您的任何意见.

李,

Cra*_*der 6

对于初学者来说,"imagerotator_show"不是一个功能; 它是一种行为的名称.当您使用add_action()函数时,Wordpress只会将您的方法添加到触发特定操作时要调用的函数/方法列表中.因此,您的第二次测试将始终响应"未找到功能".

第一个问题的最可能原因是未能声明要作为公共方法调用的方法.你也使代码变得比它需要的更难.

我在声明方法和从类中注册钩子时看到的最佳实践看起来像这样:

if ( ! class_exists( 'Foo' ) ):
  class Foo {
    function __construct() {
      add_action( 'hook_name', array( &$this, 'my_hook_implementation' ) );
    }

    function my_hook_implementation() {
      // does something
    }

    public function my_special_method() {
      // does something else
    }
  }

if ( class_exists( 'Foo' ) ):
  $MyFoo = new Foo();
Run Code Online (Sandbox Code Playgroud)

这允许您的类将其所有实现细节保密.当您需要调用my_special_method()时,您可以按如下方式执行:

$MyFoo->my_special_method();
Run Code Online (Sandbox Code Playgroud)