【发布时间】:2016-08-27 07:17:42
【问题描述】:
我正在开发一个简单的插件来计算 FB 分享的帖子和 我想使用 cron 作业创建插件类的实例。 插件的主要部分是这样的:
class PostShareCount
{
public function __construct()
{
global $wpdb;
$this->db = $wpdb;
add_action('hourly_event', 'updateAllPostsShares');
add_shortcode('social-count', array($this, 'social_shares'));
}
public function updateAllPostsShares()
{
$this->db->query('CREATE TABLE IF NOT EXISTS wp_facebook_shares(
post_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
post_shares INT NOT NULL,
post_url VARCHAR(255) NOT NULL
)');
$posts = $this->db->get_results('SELECT ID, post_date, post_name FROM '.$this->db->posts.' WHERE ID < 3');
$fb_graph = 'http://graph.facebook.com/?id=';
$site = 'http://www.example.com/';
$posts_shares = [];
foreach ($posts as $post) {
$post_url = $site.$post->post_name;
$posts_shares[$post->ID] = array();
$posts_shares[$post->ID]['post_id'] = $post->ID;
$posts_shares[$post->ID]['post_url'] = $post_url;
$api_call = $fb_graph.$site.$post->post_name;
if (isset($this->get_response_body($api_call)->shares)) {
$posts_shares[$post->ID]['post_shares'] = $this->get_response_body($api_call)->shares;
} else {
$posts_shares[$post->ID]['post_shares'] = rand(80, 1200);
}
$this->db->replace('wp_facebook_shares', $posts_shares[$post->ID], array('%d', '%s', '%d'));
}
return $posts_shares;
}
}
为了测试我的 cron,我创建了这个简单的文件:
<?php
require_once ('post-share-count.php');
$obj = new PostShareCount();
$obj->updateAllPostsShares();
?>
但每当我尝试运行它时,我都会收到此错误:
Call to undefined function add_action() in ..
知道是什么原因造成的,我该如何解决?谢谢
【问题讨论】:
-
请检查 WordPress
wp-load.php文件是否包含? -
您的简单测试 php 文件是在 WordPress 环境中运行还是直接访问?如果是这样,您将需要包含 WordPress 功能。