Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* Plugin Name: AMP Comment Counts in Excerpts
*
* @author Weston Ruter, Google
* @license GPL-2.0-or-later
* @copyright 2019 Google Inc.
*
* @wordpress-plugin
* Plugin Name: AMP Comment Counts in Excerpts
* Description: Demonstration for how to add comment counts to post excerpts (in post list) in a way they can dynamically update on an AMP Cache.
* Plugin URI: https://gist.github.com/westonruter/acb6220de53c16db552c0ece0e709bd1
* Version: 0.1.0
* Author: Weston Ruter, Google
* Author URI: https://weston.ruter.net/
* License: GNU General Public License v2 (or later)
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
add_action(
'rest_api_init',
function () {
register_rest_route(
'example/v1',
'comment-counts',
[
'methods' => 'GET',
'args' => [
'ids' => [
// @todo More validation needed, e.g. put a maximum on the number.
// @todo Add a proper schema.
'sanitize_callback' => function ( $value ) {
return wp_parse_id_list( $value );
},
'required' => true,
],
],
'callback' => function( WP_REST_Request $request ) {
$comment_counts = [];
foreach ( $request->get_param( 'ids' ) as $id ) {
$comment_counts[ $id ] = get_comment_count( $id )['approved'];
}
return $comment_counts;
},
]
);
}
);
// Demonstrate injecting comment count into Excerpt.
add_filter(
'the_excerpt',
function ( $content ) {
global $wp_query;
if ( is_archive() && $wp_query instanceof WP_Query && in_array( get_post(), $wp_query->get_posts() ) ) {
$rest_api_url = add_query_arg(
[ 'ids' => implode( ',', array_values( wp_list_pluck( $wp_query->get_posts(), 'ID' ) ) ) ],
rest_url( '/example/v1/comment-counts' )
);
ob_start();
?>
<div style="display:flex">
<span style="padding-right:1ex;">Comments:</span>
<amp-list noloading single-item items="." layout="flex-item" src="<?php echo esc_url( $rest_api_url ); ?>">
<template type="amp-mustache">{{<?php the_ID(); ?>}}</template>
<span placeholder>?</span>
</amp-list>
</div>
<?php
$amp_list = preg_replace( '/\s+/', ' ', ob_get_clean() );
$content = $amp_list . $content;
}
return $content;
},
PHP_INT_MAX
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.