我正在尝试修改一个 wordpress 插件以采用自定义类别。因此,当调用 random_post_link 时,我可以使用 random_post_link('Random Link',3) 添加自定义类别。 3 是类别名称。
下面的插件如何创建类 Random_Post_Link 的新对象?我以为您通过执行以下操作创建了新对象:
$a = new random_post_link;
但我没有在插件中看到它。我认为它通过使用钩子(Hook)在 init 函数中创建了新对象:
add_action('init', array(CLASS, 'jump'));
如果是这样的话,如何给跳转函数加参数呢?
我想我知道 add_action 是如何工作的,第二个参数应该是函数名,如何 “array(CLASS, 'jump')” 有效吗?
插件的完整代码如下:
function random_post_link($text = 'Random Post',$the_cat = 36) {
printf('<a href="%s">%s</a>', get_random_post_url(), $text);
$the_category = $the_cat;
}
function get_random_post_url() {
return trailingslashit(get_bloginfo('url')) . '?' . Random_Post_Link::query_var;
}
class Random_Post_Link {
const query_var = 'random';
const name = 'wp_random_posts';
public $the_category;
function init() {
add_action('init', array(__CLASS__, 'jump'));
// Fire just after post selection
add_action('wp', array(__CLASS__, 'manage_cookie'));
}
// Jump to a random post
function jump() {
if ( ! isset($_GET[self::query_var]) )
return;
$args = apply_filters('random_post_args', array(
'post__not_in' => self::read_cookie(),
));
$args = array_merge($args, array(
'orderby' => 'rand',
'cat' => $the_category,
'showposts' => 1,
));
$posts = get_posts($args);
if ( empty($posts) ) {
self::update_cookie(array());
unset($args['post__not_in']);
$posts = get_posts($args);
}
if ( empty($posts) )
wp_redirect(get_bloginfo('url'));
$id = $posts[0]->ID;
wp_redirect(get_permalink($id));
die;
}
// Collect post ids that the user has already seen
function manage_cookie() {
if ( ! is_single() )
return;
$ids = self::read_cookie();
$id = $GLOBALS['posts'][0]->ID;
if ( count($ids) > 200 )
$ids = array($id);
elseif ( ! in_array($id, $ids) )
$ids[] = $id;
self::update_cookie($ids);
}
private function read_cookie() {
return explode(' ', @$_COOKIE[self::name]);
}
private function update_cookie($ids) {
setcookie(self::name, trim(implode(' ', $ids)), 0, '/');
}
}
Random_Post_Link::init();
最佳答案
一些 WordPress 作者使用 PHP 中的类结构来基本上减少全局变量。该类是某种“单例”,因此通常不会实例化(代码在底部调用 Random_Post_Link::init();
)。类函数被视为类成员,而不是实例成员,例如,有点像其他语言中的 Math.max()。
__CLASS__
php 关键字只是当前类的标记,因此在传递时,可调用对象变为 Random_Post_Link::method()
或 array( ' Random_Post_Link', '方法')
如果您需要取消 Hook ,请尝试 remove_action( 'init', array( 'Random_Post_Link, 'jump' ) );
(另请注意,以这种方式使用的方法应声明为 static function jump() {...}
)
附言进一步说明:
http://php.net/manual/en/language.types.callable.php
array('class', 'function')
语法是 PHP 的东西,而 WordPress 操作需要一个 callable
,它可以是任何 PHP 可调用的东西。
关于php - array(__CLASS__, 在 wordpress 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3732083/