2009-10-23 71 views
8

我试图从一个插件添加一些功能,我已经成为一个WordPress主题,但我有点小喜悦。这些文档并不能真正帮助我解决问题,所以也许这里有人可以提供帮助。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'; 
    } 
?> 

目前,所有我曾经看到的是“没有”,“不发现功能”。感谢您的任何意见。

Lee,

+0

请注意,这应该对所有WordPress主题设计师有所帮助:http://devideas.blogetery.com/testing-wordpress-themes-easily/ – Sarfraz 2010-04-07 13:51:15

回答

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(); 
+0

感谢您的输入。我会尝试一下 – 2009-10-26 10:15:42

+0

我很好奇为什么你通过第4行的引用传递了'$ this'。我是使用面向WordPress插件的OO表单的新手。 – Andrew 2012-07-24 17:01:18

1

@andrew因为我无法评论,我想我会回答你的补充问题。请参阅:

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

,其中解释,从一个对象定义一个回调函数时,你必须使用阵列功能。它基本上是说从对象$ this获得函数'my_hook_implementation'并将其用作add动作钩子的回调参数。这是因为您在该对象的范围内定义了该函数,并且您必须定义该范围才能让PHP知道您在说什么函数。范围是由变量$ this引用的对象。