Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a custom post type called Neighborhoods, which stores information about various neighborhoods of a city. Each neighborhood also has a Facebook page. What I'd like to do is for each neighborhood, use the Facebook Graph to grab the number of likes of the page and save them in the WordPress database to display in various parts of my website.

I don't know exactly what code to use, but here is the basic outline:

Run this once a day:
    Query neighborhood post type in the database
    For each neighborhood:
        $data = json_decode(file_get_contents('https://graph.facebook.com/neighborhoodURL'));
        $numberOfLikes = $data->likes;
        Save $numberOfLikes in it's own field in the database

And once that's set, I should be able to call the number of likes field in the loop.

Anyone know the best way to do this?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

First, you'll need to set up a WordPress cron job, and take note of its shortcomings...

Using the Codex example, this is a structure of how this could be done:

add_action( 'my_daily_event', 'do_this_daily' );
add_action( 'wp', 'my_activation' );

function do_this_daily() 
{
    // 1) Use get_posts to retrieve your Post Type

    // 2) Iterate through the resulting posts and grab the Facebook Page custom field of each post

    // 3) Request FB Graph info as follows
    $fb = wp_remote_get( 'https://graph.facebook.com/Stack-Exchange', array( 'timeout' => 120, 'httpversion' => '1.1' ) );
    if ( $fb['response']['code'] == '200' )
    {
        $fb_array = json_decode( $fb['body'], true );
        echo '<pre>' . print_r( $fb_array, true ) . '</pre>';
    }

    // 4) Update the Likes custom field of each post with $fb_array['likes'] value
}

function my_activation() {
    if ( !wp_next_scheduled( 'my_daily_event' ) ) {
        wp_schedule_event( time(), 'daily', 'my_daily_event' );
    }
}
share|improve this answer
    
Great explanation. Thank you! –  kmmathis Nov 17 '12 at 1:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.