-
Notifications
You must be signed in to change notification settings - Fork 1
Get Popular Posts
Takahashi Fumiki edited this page Sep 24, 2021
·
1 revision
GaComunicator->popular_posts()
method and it's syntax sugar ga_communicator_popular_posts()
will:
- Request page views and path information from Analytics Reporting API.
- Convert path information to post ID.
- Query posts with IDs and returns
WP_Query
object.
With this method, you can get popular posts in WordPress way.
$query
An array merged into new WP_Query( $query )
. If you need just post type faq
, $query
is like below:
$query = [
'post_type' => 'faq',
];
$conditions
An array of conditions to filter results. Default is defined inside code like below:
$conditions = [
'path_regexp' => $this->get_permalink_filter(), // Default is permalink structure.
'number' => 10, // Post count.
'days_before' => 30,
'offset_days' => 0,
'start' => '',
'end' => '',
];
To get posts well visited in recent 7 days(e.g. weekly ranking), specify days_before
. offset_days
works as an adjustment.
// Get Sun-Mon last week ranking.
$contiond = [
'days_before' => 7,
'offset_days' => date_i18n( 'w' ), // Set origin to Sunday.
];
If you need a list of popular posts in a specific range(e.g. Olympic year), specify start
and end
in YYYY-mm-dd.
$conditions = [
'start' => '2020-06-01', // As you know, this hasn't actually happen.
'end' => '2020-08-31',
];
Let's get popular posts post_type=faq
in recent 7 days.
$query = \Kunoichi\GaCommunicator::get_instance()->popular_posts( [
'post_type' => 'faq',
], [
'path_regexp' => '^/faq/[0-9]+/$', // Regular expression to filter path.
'number' => 10, // Number of posts.
'days_before' => 7, // Recent 7 days.
] );
if ( $query ) {
while ( $query->have_posts() ) {
$query->the_post();
// You can do things in WordPress way.
get_template_part( 'template-parts/loop', get_post_type() );
}
}
Cache result makes your site's performance nicer.