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

时间:2009-10-23 18:19:04

标签: wordpress plugins wordpress-plugin themes

我正在尝试从我已经制作成一个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'));
}

主题标题页中的部分:

<?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';
    }
?>

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

3 个答案:

答案 0 :(得分: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();

这允许您的类将其所有实现细节保密。当您需要调用my_special_method()时,请按以下步骤操作:

$MyFoo->my_special_method();

答案 1 :(得分:1)

由于我不能发表评论,所以我认为我会回答你的辅助问题。参见:

http://net.tutsplus.com/tutorials/wordpress/create-wordpress-plugins-with-oop-techniques/

在说明从对象定义回调函数时,必须使用数组函数。它基本上是从对象$ this获取函数'my_hook_implementation'并将其用作add action hook的回调参数。这是因为你在对象范围内定义了函数,你必须定义范围,以便PHP知道你在说什么函数。范围是变量$ this。

引用的对象

答案 2 :(得分:0)

您只需要在主题内使用do_action()功能。

如果您希望函数generateHtml出现在header.php中,则只需要打开header.php文件并将<?php do_action('imagerotator_show'); ?>粘贴到所需的位置,即可在其中调用函数。 / p>