Enabled AJAX update for widgets

This commit is contained in:
Stefan Kalscheuer 2017-12-10 21:15:55 +01:00
parent 7b0a512c2b
commit 2d5dde9664
4 changed files with 157 additions and 56 deletions

View File

@ -34,6 +34,9 @@ class WPLiveticker2_Widget extends WP_Widget {
* @param array $instance The settings for the particular instance of the widget. * @param array $instance The settings for the particular instance of the widget.
*/ */
public function widget( $args, $instance ) { public function widget( $args, $instance ) {
// Notify WPLT2 class that widget is present.
WPLiveticker2::mark_widget_present();
$instance = self::fill_options_with_defaults( $instance ); $instance = self::fill_options_with_defaults( $instance );
$before_widget = isset( $args['before_widget'] ) ? $args['before_widget'] : ''; $before_widget = isset( $args['before_widget'] ) ? $args['before_widget'] : '';
$after_widget = isset( $args['after_widget'] ) ? $args['after_widget'] : ''; $after_widget = isset( $args['after_widget'] ) ? $args['after_widget'] : '';
@ -59,7 +62,14 @@ class WPLiveticker2_Widget extends WP_Widget {
echo $before_title . esc_html( $title ) . $after_title; echo $before_title . esc_html( $title ) . $after_title;
} }
echo '<ul class="wplt2-widget">'; echo '<ul class="wplt2-widget';
if ( '1' === $ajax ) {
echo ' wplt2-widget-ajax" '
. 'data-wplt2-ticker="' . esc_attr( $category ) . '" '
. 'data-wplt2-limit="' . esc_attr( $count ) . '" '
. 'data-wplt2-last="' . esc_attr( time() );
}
echo '">';
$args = array( $args = array(
'post_type' => 'wplt2_tick', 'post_type' => 'wplt2_tick',
@ -76,11 +86,12 @@ class WPLiveticker2_Widget extends WP_Widget {
$cnt = 0; $cnt = 0;
while ( $wp_query->have_posts() && ( $count <= 0 || ++ $cnt < $count ) ) { while ( $wp_query->have_posts() && ( $count <= 0 || ++ $cnt < $count ) ) {
$wp_query->the_post(); $wp_query->the_post();
echo '<li>' // @codingStandardsIgnoreLine
. '<span class="wplt2-widget-time">' . esc_html( get_the_time( 'd.m.Y - H.i' ) ) . '</span>' echo WPLiveticker2::tick_html_widget(
. '<span class="wplt-widget-content' esc_html( get_the_time( 'd.m.Y - H.i' ) ),
. ( ( '1' === $highlight && get_the_time( 'U' ) > ( time() - $highlight_time ) ) ? '_new' : '' ) get_the_title(),
. '"><br>' . the_title() . '</span></li>'; ( '1' === $highlight && get_the_time( 'U' ) > ( time() - $highlight_time ) )
);
} }
echo '</ul>'; echo '</ul>';

View File

@ -36,12 +36,20 @@ class WPLiveticker2 {
protected static $_options; protected static $_options;
/** /**
* Plugin options. * Marker if shortcode is present.
* *
* @var boolean $shortcode_present * @var boolean $shortcode_present
*/ */
protected static $shortcode_present = false; protected static $shortcode_present = false;
/**
* Marker if widget is present.
*
* @var boolean $shortcode_present
*/
protected static $widget_present = false;
/** /**
* Plugin initialization. * Plugin initialization.
* *
@ -239,7 +247,7 @@ class WPLiveticker2 {
*/ */
public static function enqueue_styles() { public static function enqueue_styles() {
// Only add if shortcode is present. // Only add if shortcode is present.
if ( self::$shortcode_present ) { if ( self::$shortcode_present || self::$widget_present ) {
wp_enqueue_style( wp_enqueue_style(
'wplt-css', 'wplt-css',
WPLT2_BASE . 'styles/wp-liveticker2.css', WPLT2_BASE . 'styles/wp-liveticker2.css',
@ -253,24 +261,27 @@ class WPLiveticker2 {
* Register frontend JS. * Register frontend JS.
*/ */
public static function enqueue_scripts() { public static function enqueue_scripts() {
wp_enqueue_script( // Only add if shortcode is present.
'wplt2-js', if ( self::$shortcode_present || self::$widget_present ) {
WPLT2_BASE . 'scripts/wp-liveticker2.js', wp_enqueue_script(
array( 'jquery' ), 'wplt2-js',
self::VERSION, WPLT2_BASE . 'scripts/wp-liveticker2.js',
true array( 'jquery' ),
); self::VERSION,
true
);
// Add endpoint to script. // Add endpoint to script.
wp_localize_script( wp_localize_script(
'wplt2-js', 'wplt2-js',
'ajax_object', 'ajax_object',
array( array(
'ajax_url' => admin_url( 'admin-ajax.php' ), 'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'wplt2_update-ticks' ), 'nonce' => wp_create_nonce( 'wplt2_update-ticks' ),
'poll_interval' => self::$_options['poll_interval'] * 1000, 'poll_interval' => self::$_options['poll_interval'] * 1000,
) )
); );
}
} }
/** /**
@ -287,8 +298,18 @@ class WPLiveticker2 {
$res = array(); $res = array();
// @codingStandardsIgnoreLine Sanitization of arrayhandled on field level. // @codingStandardsIgnoreLine Sanitization of arrayhandled on field level.
foreach ( wp_unslash( $_POST['update'] ) as $update_req ) { foreach ( wp_unslash( $_POST['update'] ) as $update_req ) {
if ( is_array( $update_req ) && isset( $update_req['s'] ) ) { if ( is_array( $update_req ) && ( isset( $update_req['s'] ) || isset( $update_req['w'] ) ) ) {
$slug = sanitize_text_field( $update_req['s'] ); if ( isset( $update_req['s'] ) ) {
$is_widget = false;
$slug = sanitize_text_field( $update_req['s'] );
} elseif ( isset( $update_req['w'] ) ) {
$is_widget = true;
$slug = sanitize_text_field( $update_req['w'] );
} else {
// Should never occur, but for completenes' sake...
break;
}
$limit = ( isset( $update_req['l'] ) ) ? intval( $update_req['l'] ) : - 1; $limit = ( isset( $update_req['l'] ) ) ? intval( $update_req['l'] ) : - 1;
$last_poll = ( isset( $update_req['t'] ) ) ? intval( $update_req['t'] ) : 0; $last_poll = ( isset( $update_req['t'] ) ) ? intval( $update_req['t'] ) : 0;
@ -313,13 +334,26 @@ class WPLiveticker2 {
$out = ''; $out = '';
while ( $query->have_posts() ) { while ( $query->have_posts() ) {
$query->the_post(); $query->the_post();
$out .= self::tick_html( get_the_time( 'd.m.Y H.i' ), get_the_title(), get_the_content() ); if ( $is_widget ) {
$out .= self::tick_html_widget( get_the_time( 'd.m.Y H.i' ), get_the_title(), false );
} else {
$out .= self::tick_html( get_the_time( 'd.m.Y H.i' ), get_the_title(), get_the_content(), $is_widget );
}
}
if ( $is_widget ) {
$res[] = array(
'w' => $slug,
'h' => $out,
't' => time(),
);
} else {
$res[] = array(
's' => $slug,
'h' => $out,
't' => time(),
);
} }
$res[] = array(
's' => $slug,
'h' => $out,
't' => time(),
);
} }
} }
// Echo JSON encoded result set. // Echo JSON encoded result set.
@ -329,6 +363,15 @@ class WPLiveticker2 {
exit; exit;
} }
/**
* Mark that Widget is present.
*
* @return void
*/
public static function mark_widget_present() {
self::$widget_present = true;
}
/** /**
* Update options. * Update options.
* *
@ -359,14 +402,37 @@ class WPLiveticker2 {
/** /**
* Generate HTML code for a tick element. * Generate HTML code for a tick element.
* *
* @param string $time Tick time (readable). * @param string $time Tick time (readable).
* @param string $title Tick title. * @param string $title Tick title.
* @param string $content Tick content. * @param string $content Tick content.
* @param boolean $is_widget Is the code for Widget.
*
* @return string HTML code of tick.
*/ */
private static function tick_html( $time, $title, $content = null ) { private static function tick_html( $time, $title, $content, $is_widget = false ) {
return '<li class="wplt2-tick">' return '<li class="wplt2-tick">'
. '<p><span class="wplt2-tick_time">' . esc_html( $time ) . '</span>' . '<p><span class="wplt2-tick_time">' . esc_html( $time ) . '</span>'
. '<span class="wplt2-tick-title">' . esc_html( $title ) . '</span></p>' . '<span class="wplt2-tick-title">' . esc_html( $title ) . '</span></p>'
. '<p class="wplt2-tick-content">' . $content . '</p></li>'; . '<p class="wplt2-tick-content">' . $content . '</p></li>';
}
/**
* Generate HTML code for a tick element in widget.
*
* @param string $time Tick time (readable).
* @param string $title Tick title.
* @param boolean $highlight Highlight element.
*
* @return string HTML code of widget tick.
*/
public static function tick_html_widget( $time, $title, $highlight ) {
$out = '<li';
if ( $highlight ) {
$out .= ' class="wplt2-widget-new"';
}
return $out . '>'
. '<span class="wplt2-widget-time">' . esc_html( $time ) . '</span>'
. '<span class="wplt2-widget-title">' . $title . '</span>'
. '</li>';
} }
} }

View File

@ -10,12 +10,15 @@ WPLT2.init = function () {
WPLT2.ticker = jQuery("ul.wplt2-ticker-ajax").map(function () { WPLT2.ticker = jQuery("ul.wplt2-ticker-ajax").map(function () {
return {s: jQuery(this).data('wplt2Ticker'), e: this}; return {s: jQuery(this).data('wplt2Ticker'), e: this};
}); });
WPLT2.widgets = jQuery("ul.wplt2-widget-ajax").map(function () {
return {s: jQuery(this).data('wplt2Ticker'), e: this};
});
// Extract AJAX settings. // Extract AJAX settings.
WPLT2.ajaxURL = ajax_object.ajax_url; WPLT2.ajaxURL = ajax_object.ajax_url;
WPLT2.nonce = ajax_object.nonce; WPLT2.nonce = ajax_object.nonce;
WPLT2.pollInterval = ajax_object.poll_interval; WPLT2.pollInterval = ajax_object.poll_interval;
// Trigger update, if necessary. // Trigger update, if necessary.
if (WPLT2.ticker.length > 0 && WPLT2.pollInterval > 0) { if ((WPLT2.ticker.length > 0 || WPLT2.widgets.length) && WPLT2.pollInterval > 0) {
setTimeout(WPLT2.update, WPLT2.pollInterval); setTimeout(WPLT2.update, WPLT2.pollInterval);
} }
}; };
@ -25,15 +28,20 @@ WPLT2.init = function () {
*/ */
WPLT2.update = function () { WPLT2.update = function () {
// Extract ticker-slug, limit and timestamp of last poll. // Extract ticker-slug, limit and timestamp of last poll.
const updateReq = jQuery.map(WPLT2.ticker, function (e, i) { const updateReq = jQuery.merge(
return {s: e.s, l: jQuery(e.e).data('wplt2Limit'), t: jQuery(e.e).data('wplt2Last')}; jQuery.map(WPLT2.ticker, function (e, i) {
}); return {s: e.s, l: jQuery(e.e).data('wplt2Limit'), t: jQuery(e.e).data('wplt2Last')};
}),
jQuery.map(WPLT2.widgets, function (e, i) {
return {w: e.s, l: jQuery(e.e).data('wplt2Limit'), t: jQuery(e.e).data('wplt2Last')};
})
);
// Issue AJAX request. // Issue AJAX request.
jQuery.post( jQuery.post(
WPLT2.ajaxURL, WPLT2.ajaxURL,
{ {
'action' : 'wplt2_update-ticks', 'action' : 'wplt2_update-ticks',
'_ajax_nonce': WPLT2.nonce, '_ajax_nonce': WPLT2.nonce,
'update' : updateReq 'update' : updateReq
}, },
@ -44,15 +52,12 @@ WPLT2.update = function () {
jQuery.each(update, function (i, u) { jQuery.each(update, function (i, u) {
jQuery.each(WPLT2.ticker, function (j, t) { jQuery.each(WPLT2.ticker, function (j, t) {
if (t.s === u.s) { if (t.s === u.s) {
// Prepend HTML of new ticks. WPLT2.updateHTML(t.e, u.h, u.t);
jQuery(t.e).prepend(u.h); }
// Remove tail, if limit is set. });
const l = jQuery(t.e).data('wplt2Limit'); jQuery.each(WPLT2.widgets, function (j, t) {
if (l > 0) { if (t.s === u.w) {
jQuery(t.e).find('li').slice(l).remove(); WPLT2.updateHTML(t.e, u.h, u.t);
}
// Update last poll timestamp.
jQuery(t.e).data('wplt2Last', u.t);
} }
}); });
}); });
@ -66,6 +71,25 @@ WPLT2.update = function () {
); );
}; };
/**
* Do actual update of HTML code.
*
* @param e The element.
* @param h The new HTML code.
* @param t Timestamp of update.
*/
WPLT2.updateHTML = function(e, h, t) {
// Prepend HTML of new ticks.
jQuery(e).prepend(h);
// Remove tail, if limit is set.
const l = jQuery(e).data('wplt2Limit');
if (l > 0) {
jQuery(e).find('li').slice(l).remove();
}
// Update last poll timestamp.
jQuery(e).data('wplt2Last', t);
};
jQuery(document).ready(function ($) { jQuery(document).ready(function ($) {
// Trigger periodic update of livetickers. // Trigger periodic update of livetickers.
WPLT2.init(); WPLT2.init();

View File

@ -42,7 +42,7 @@ defined( 'ABSPATH' ) || exit;
</td> </td>
<td> <td>
<select id="<?php echo esc_attr( $this->get_field_id( 'count' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'count' ) ); ?>"> <select id="<?php echo esc_attr( $this->get_field_id( 'count' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'count' ) ); ?>">
<option value="0"<?php if ( '0' === $count ) { <option value="-1"<?php if ( '-1' === $count ) {
echo ' selected="selected"'; echo ' selected="selected"';
} ?>><?php esc_html_e( 'all', 'wplt2' ); ?></option> } ?>><?php esc_html_e( 'all', 'wplt2' ); ?></option>
<option value="1"<?php if ( '1' === $count ) { <option value="1"<?php if ( '1' === $count ) {
@ -120,7 +120,7 @@ defined( 'ABSPATH' ) || exit;
<td> <td>
<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'ajax' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'ajax' ) ); ?>" type="checkbox" value="1"<?php if ( '1' === $ajax ) { <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'ajax' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'ajax' ) ); ?>" type="checkbox" value="1"<?php if ( '1' === $ajax ) {
echo ' checked="checked"'; echo ' checked="checked"';
} ?> disabled="disabled" /> } ?> />
<small><?php esc_html_e( '(enables ajax)', 'wplt2' ); ?></small> <small><?php esc_html_e( '(enables ajax)', 'wplt2' ); ?></small>
</td> </td>
</tr> </tr>