add_action() not defined error – wordpress plugin

i’m working on a simple plugin to count FB shares of post and
i want to create instance of the plugin class using a cron job.
the main part of the plugin is this:

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

and for a test to my cron i created this simple file:

Read More
<?php
require_once ('post-share-count.php');
$obj = new PostShareCount();
$obj->updateAllPostsShares();
?>

but whenever i try to run it i get this error:

Call to undefined function add_action() in ..

any idea what is causing this and how can i fix it? thx

Related posts

1 comment

  1. There is simpler way, how to test your cronjobs:

    Install WP Crontrol plugin.
    Now, you can run your crons from administration.

    1. Go to WordPress Administration: Tools -> Cron Events
    2. If your plugin is working properly, you should see your scheduled hook name here.
    3. Click on Run Now

    Calling function directly from PHP file

    If you need for some reason to call plugin functions directly from testing PHP file, don’t forget to include wp-load.php.

    Example (file is in same directory as wp-load.php):

    <?php
    include ('wp-load.php');
    
    $obj = new PostShareCount();
    $obj->updateAllPostsShares();
    
    ?>
    

Comments are closed.