Create a gist now

Instantly share code, notes, and snippets.

Tutorial WordPress Heartbeat API

#Tutorial WordPress Heartbeat API - Take Two

Una versión mejorada del excelente tutorial por Ubikom.

<?php
/*
Plugin Name: Live Comment Alert System
Plugin URI: http://www.ubikom.es/blog
Description: Demostrativo de la nueva HeartBeat API
Version: 1.1
Author: Ubikom, brasofilo
Author URI: http://www.ubikom.es/blog
License: GPLv2 or later
*/
 
// No permitimos que el script se carge directamente.
!defined( 'ABSPATH' ) AND exit(
        "<pre>Que pasa! soy solo un plugin, 
            <h1>&iquest;que buscas exactamente?" );

add_action(
	'plugins_loaded',
	array ( B5F_Ubikom_Comment_Alert_Plugin::get_instance(), 'plugin_setup' )
);

class B5F_Ubikom_Comment_Alert_Plugin
{
	protected static $instance = NULL;
	public $plugin_url = NULL;
	
	public function __construct() {}

    public static function get_instance()
	{
		NULL === self::$instance and self::$instance = new self;
		return self::$instance;
	}

    /**
     * Empieza nuestro trabajo
     *
     * solo para usuarios registrados
     * 
     * @wp-hook plugins_loaded
     */
	public function plugin_setup()
	{
        if( !is_user_logged_in() )
            return;
        
		$this->plugin_url    = plugins_url( '/', __FILE__ );
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
        add_filter( 'heartbeat_received', array( $this, 'heartbeat_received' ), 10, 2 );
    }
    
    /**
     * Cargar scripts y styles
     * 
     * @wp-hook wp_enqueue_scripts
     */
    public function enqueue()
    {
        wp_enqueue_script( 
            'comment-alert', 
            $this->plugin_url . 'comment-alert.js', 
            array( 'heartbeat' ) 
        );
        wp_enqueue_style( 
            'coment-alert-style', 
            $this->plugin_url . 'comment-alert.css' 
        );
    }

    /**
     *  Esta funcion es llamada por cada "latido" del heartbeart.
     * 
     * @param arrayt $response
     * @param array  $data
     * @return array
     * @wp-hook heartbeat_received
     */
    public function heartbeat_received( $response, $data )
    {
        if( isset( $data["action"] ) && $data["action"] == "commentAlert" )
        {
            $user = wp_get_current_user();
            $comments = $this->lastComments( $user->ID );
            $response['comments'] = json_encode( $comments );
            $response['total'] = count( $comments );
        }
        return $response;
    }

    /**
     *  Recogemos los ultimos comentarios desde su ultimo acceso 
     * 
     * @global object $wpdb
     * @param int $user_id
     * @return object
     */
    private function lastComments( $user_id )
    {
        global $wpdb;
        // Recogemos la ultima vez que el usuario recogio los comentarios
        $last_comment_access = get_user_meta( $user_id, 'last_comment_access', true );

        // Si no existe, cogemos los comentarios de la ultima semana
        if( $last_comment_access == false )
            $last_comment_access = date( 'Y-m-d H:i:s', time() - 604800 );

        $comments = $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_date > '" . $last_comment_access . "' LIMIT 10" );

        // Actualizamos el momento en el que el usuairo ha recogido los comentarios
        update_user_meta( $user_id, 'last_comment_access', date( 'Y-m-d H:i:s' ) );

        return $comments;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment