Top Posts & Pages widget: applies filter post type choice filter after calculating total posts to display
The updated Top Posts & Pages widget from Jetpack 3.6 is applying the types choice after the total is collected, which in most cases results in a mismatch with the desired total. This is hard for me to explain with words, so how about an example? :)
http://macmanx.com/ has 1,276 Posts, with stats going back to the day Jetpack was first released, yet when I set my Top Posts & Pages widget to display my top 10 posts, it only displays 6. If I set it to display my top 10 posts and pages, it displays 10, and 4 of those are pages.
In the above example, rather than fetching my top 10 posts, the widget fetches my top 10 posts and pages, then filters out the 6 posts from that.
Also reported here: https://wordpress.org/support/topic/top-posts-and-pages-widget-displays-too-many-entries-when-filtered-by-page-types?replies=1&view=all
One suggestion for this is to pull a higher number (whatever reasonable... 20, 50, etc), then filter them locally to return the specific number of posts or pages.
Also noting that this would also be resolved by #2196, though my earlier suggestion would work depending on the timeline for the rewrite.
Top Posts & Pages (JetPack) stopped working, I had 10 posts displaying yesterday, now it's only showing one. What can be wrong?
@scriptgeni Can you please use Jetpack's Debugger module to send us some more information about your site?
- Go to the Jetpack page in your dashboard.
- Click on the Debug link appearing at the bottom of the page.
- Click the link that says "click here to contact Jetpack support."
- Fill in the description box and your name and email address.
- Click the "Contact Support" button.
Thanks!
I recently fixed the issue #2196 mentioned above. I can tell you that in resolving that issue, it did not fix this issue. This is due to the way Top Posts are retrieved from the server.
Issue 1: The Top Posts endpoint on the REST API does not support filtering by post type. So if the widget is setup to view the top posts of a not-often-viewed custom post type, those posts might be low on the overall list. Meaning, it possibly could not show up on the retrieved list of 10 or so posts. You could try reconnecting and retrieving more posts, but it would be better to fix it on the server end, in my opinion.
Issue 2: In addition, the REST endpoint restricts the max number of posts per day and doesn't retrieve an overall list of top posts. This probability won't affect most sites with the default option of top posts over 2 days, but if a site wants the top posts over a longer period, such as a month, this could allow a post that is visited more often over time to be cut off by posts that were only popular for a short time.
After looking through the public-api code, to fix the first issue would require a change to the select statement used to retrieve the list to something like SELECT from $pageviews_table JOIN $site_posts_table WHERE post_type IN ($post_types). However, for the second issue, the select statement is more complex with either a temp table or UNION ALL needed to collect a full list of posts. Of course, you could always run multiple select statements, merge the results, and filter using PHP as well. But I don't have the full view of how the database structure of WP.com is setup so there might be an easier way,
Also reported here: https://wordpress.org/support/topic/top-posts-category-filter-top-posts-limit-question?replies=1&view=all
Also reported here: https://wordpress.org/support/topic/popular-posts-widgets?replies=1
reported in 2699464-t
I'll just add some weight to this being a pretty killer 'bug'. It leaves the user experience of this plugin really really frustrating, where the options which you expose in the widget, in a sense and in practice, seem utterly broken. When I ask for 10 posts, of post type X, If that is a low-view post type, I will get 0 items displaying, even though I know there are posts of that type and I know they have views. Of course this is still 'logical' because you used the word 'max' posts, but it also means that the plugin is all but useless for anything other than a standard top 5 of anyposts/page. Which is fine if that's all it was sold as, but which is again, so frustrating when the UI suggests that the plugin could be so much more powerful.
In parting can i suggest that the ideal functionality for usability of the plugin would be:
Specify number of posts (exact!): X (filled in as much as possible via your stats system, and then padded with extra/fallback posts if not enough via stats) Specify post type: Y (only caveat here is if I ask for 10 posts, but my chosen post type literally only has 6 posts published, you obviously couldn't show 10)
I do appreciate the work gone into this plugin, and it seems so close to being really really awesome, if only we could get more logical, predictable results!
Thanks
Also reported here: https://wordpress.org/support/topic/exclude-an-entire-tags-from-top-posts?replies=5&view=all#post-8655589
Seeing you have this set for 4.4 milestone, but can't seem to find what version you're currently at? we have a client waiting on this and after a month of waiting we're at the point of needing to switch to another system if there's no movement :( any ideas when it might be out?
@t22james We're about to release 4.2. This issue is indeed scheduled for 4.4, for some of the reasons outlined above.
Until the problem is fixed, you could try using the jetpack_top_posts_widget_count filter to change the number of posts being displayed:
https://developer.jetpack.com/hooks/jetpack_top_posts_widget_count/
However, you would still run into the same issue; the number you would pick with the filter wouldn't be the final number; post types you won't want to display in the widget would then be withdrawn from that number.
Another alternative would be to use the filter above to query for a large number of posts (20 for example), and then use the jetpack_widget_get_top_posts filter to limit the number of displayed posts to 10:
function jeherve_more_top_posts() {
return '20';
}
add_filter( 'jetpack_top_posts_widget_count', 'jeherve_more_top_posts' );
function jeherve_only_ten_top_posts( $posts, $post_ids, $count ) {
return array_splice( $posts, 10 );
}
add_filter( 'jetpack_widget_get_top_posts', 'jeherve_only_ten_top_posts', 10, 3 );
That should solve your issue.
@jeherve hey thanks for the update and and attempt at temporary fix, but I think that still suffers the same problem, in that both of those filters run BEFORE the set of posts is filtered by post type. So again we can have a set of 10 returning from a larger set of 20 (as your snippet implies), but then this code runs:
(around line 279 of top-posts.php)
// Filter the returned posts. Remove all posts that do not match the chosen Post Types.
if ( isset( $types ) ) {
foreach ( $posts as $k => $post ) {
if ( ! in_array( $post['post_type'], $types ) ) {
unset( $posts[$k] );
}
}
}
which then knocks those 10 down to potentially 0. I think that is back to the OP issue.
That's a good point, my bad, I should have double checked at what point jetpack_widget_get_top_posts was applied.
You could still use that filter, though, and do the post type filtering there. Once you've done that, you'll have a list of posts matching your selection, and you can then check the number of posts in the array, and make sure you only have 10 posts. You could then have it return nothing if it doesn't have enough posts to fit your needs.
I know that's still a work-around though, and we'll need to get the bug fixed. We'll update this issue as soon as we make progress.
@jeherve yep nice I had thought the same, then went to sleep ;) but here is a snippet I've ended up with for now:
For anyone coming across this issue, try this out... this should return an exact number of posts by using the posts returned by top posts plugin, padded out by some 'latest' posts if not enough top posts were found. NOTE that this requires hard coding the post count, which will override your setting in the admin widget itself. You also need to hardcode post-types to MATCH what you have set in your widget. If you have different widgets with different settings, you'll need to add some if statements and replicate them in the code below.
FYI this should become redundant when this ticket is resolved.
add to functions.php, and define $type_of_posts and $num_of_posts
// force up the number of posts requested
function jeherve_more_top_posts() {
return '100';
}
add_filter( 'jetpack_top_posts_widget_count', 'jeherve_more_top_posts' );
// alter the set of posts returned in top posts
function jeherve_relimit_topposts_displayed_count( $posts, $post_ids, $count ) {
// define the post types you want to include in your widget - this should match your settings in admin widget
$type_of_posts = array('post', 'custom_post1', 'custom_post2');
// define how any posts to display (WILL display this number, so long as you have this many posts in your DB) - this will override your setting in admin widget
$num_of_posts = 5;
// create a set of posts, using top posts plugin, and padding with latest posts from your chosen post types, if not enough top posts were found
$posts = create_better_topposts($posts, $type_of_posts, $num_of_posts, $offset);
return $posts;
}
add_filter( 'jetpack_widget_get_top_posts', 'jeherve_relimit_topposts_displayed_count', 10, 3 );
// our custom function to supplement the native top posts query
function create_better_topposts($posts, $type_of_posts, $num_of_posts){
// remove any posts which don't match our desired set
// we do this here, so that the existing filter in top posts plugin, which runs AFTER $count is applied, is pre-empted, and thus we will get our exact number of desired posts.
foreach ( $posts as $k => $post ) {
if ( !in_array($post['post_type'], $type_of_posts) ) {
unset( $posts[$k] );
}
}
// reindex posts and count
$posts = array_values($posts);
$remaining_post_count = count($posts);
// remove surplus any posts
if($remaining_post_count > $num_of_posts){
array_splice( $posts, $num_of_posts );
// else, pad with extra posts (latest of desired post type/s) if not enough popular posts were returned
} else if($remaining_post_count < $num_of_posts){
//make array of post ids we already have from 'most popular', so we don't double up
$existing_post_ids = array_map(function($post) {
return $post['post_id'];
}, $posts);
$padding_posts_required = ($num_of_posts - $remaining_post_count);
$args = array(
'posts_per_page' => $padding_posts_required,
'orderby' => 'date',
'order' => 'DESC',
'post__not_in' => $existing_post_ids,
'post_type' => $type_of_posts,
'post_status' => 'publish',
'ignore_sticky_post'=> true
);
// query extra posts
$padding_posts = get_posts( $args );
// conform the new posts into our existing top-posts-plugin friendly array
foreach ( $padding_posts as $padding_post ) {
// Both get HTML stripped etc on display
if ( empty( $padding_post->post_title ) ) {
$title_source = $padding_post->post_content;
$title = wp_html_excerpt( $title_source, 50 );
$title .= '…';
} else {
$title = $padding_post->post_title;
}
$post_id = $padding_post->ID;
$permalink = get_permalink( $post_id );
$post_type = $padding_post->post_type;
$posts[] = compact( 'title', 'permalink', 'post_id', 'post_type' );
}
}
return $posts;
}
thanks for your input!
@jeherve hmm though am i right that this line (471):
$post_view_posts = stats_get_csv( 'postviews', array( 'days' => absint( $days ), 'limit' => 11 ) );
will still be limiting the pool of posts to 11? though curiously when I am printing the $posts that is being passed into jetpack_widget_get_top_posts filter, i only seem to ever have an array with 10 items. so actually even the fix above, though it helps, still can never increase the pool of popular posts available above that hardcoded 11....
OK, so final code where I'm now pretty much re-querying everything, to bypass all hardcoded result limits.
This will ensure you get exactly your desired number of posts, of your desired pos type/s (so long as you have enough in your database), using as many popular posts as possible, and padding any shortfall with extras from latest posts.
add to functions.php, and define $type_of_posts, $num_of_posts and $days
function jeherve_more_top_posts() {
// force up the number of posts requested (this bit may be redundant now)
return '100';
}
add_filter( 'jetpack_top_posts_widget_count', 'jeherve_more_top_posts' );
// alter the set of posts returned in top posts
function jeherve_relimit_topposts_displayed_count( $posts, $post_ids, $count ) {
// define the post types you want to include in your widget - this will override your settings in admin widget
$type_of_posts = array('post', 'custom_post1', 'custom_post2');
// define how any posts to display (WILL display this number, so long as you have this many posts in your DB) - this will override your setting in admin widget
$num_of_posts = 5;
// days of data to use
$days = 3;
// create a set of posts, using top posts plugin, and padding with latest posts from your chosen post types, if not enough top posts were found
$posts = create_better_topposts($posts, $type_of_posts, $num_of_posts, $days);
return $posts;
}
add_filter( 'jetpack_widget_get_top_posts', 'jeherve_relimit_topposts_displayed_count', 10, 3 );
// our custom function to essentially replace the native top posts query
function create_better_topposts($posts, $type_of_posts, $num_of_posts, $days){
//replicating code from top-posts plugin code so that we can increase the number of results returned from their hardcoded 11, to 150... ensures we get more actual popular posts
$post_view_posts = stats_get_csv( 'postviews', array( 'days' => absint( $days ), 'limit' => 150 ) );
if ( ! $post_view_posts ) {
return array();
}
$post_view_ids = array_filter( wp_list_pluck( $post_view_posts, 'post_id' ) );
if ( ! $post_view_ids ) {
return array();
}
// overwrite jetpack posts, as we are reconstructing from scratch. crucial difference is we arn't limiting results to $count or $num posts here, we we'll only do that below, after filtering out post types
$posts = array();
foreach ( (array) $post_view_ids as $post_id ) {
$post = get_post( $post_id );
if ( ! $post )
continue;
// hide private and password protected posts
if ( 'publish' != $post->post_status || ! empty( $post->post_password ) || empty( $post->ID ) )
continue;
// Both get HTML stripped etc on display
if ( empty( $post->post_title ) ) {
$title_source = $post->post_content;
$title = wp_html_excerpt( $title_source, 50 );
$title .= '…';
} else {
$title = $post->post_title;
}
$permalink = get_permalink( $post->ID );
$post_type = $post->post_type;
$posts[] = compact( 'title', 'permalink', 'post_id', 'post_type' );
}
// remove any posts which don't match our desired set
// we do this here, so that the existing filter in top posts plugin, which runs AFTER $count is applied, is pre-empted, and thus we will get our exact number of desired posts.
foreach ( $posts as $k => $post ) {
if ( !in_array($post['post_type'], $type_of_posts) ) {
unset( $posts[$k] );
}
}
// reindex posts and count
$posts = array_values($posts);
$remaining_post_count = count($posts);
// remove any surplus posts
if($remaining_post_count > $num_of_posts){
array_splice( $posts, $num_of_posts );
// else, pad with extra posts (latest of desired post type/s) if not enough popular posts were returned
} else if($remaining_post_count < $num_of_posts){
//make array of post ids we already have from 'most popular', so we don't double up
$existing_post_ids = array_map(function($post) {
return $post['post_id'];
}, $posts);
$padding_posts_required = ($num_of_posts - $remaining_post_count);
$args = array(
'posts_per_page' => $padding_posts_required,
'orderby' => 'date',
'order' => 'DESC',
'post__not_in' => $existing_post_ids,
'post_type' => $type_of_posts,
'post_status' => 'publish',
'ignore_sticky_post'=> true
);
// query extra posts
$padding_posts = get_posts( $args );
// conform the new posts into our existing top-posts-plugin friendly array
foreach ( $padding_posts as $padding_post ) {
// Both get HTML stripped etc on display
if ( empty( $padding_post->post_title ) ) {
$title_source = $padding_post->post_content;
$title = wp_html_excerpt( $title_source, 50 );
$title .= '…';
} else {
$title = $padding_post->post_title;
}
$post_id = $padding_post->ID;
$permalink = get_permalink( $post_id );
$post_type = $padding_post->post_type;
$posts[] = compact( 'title', 'permalink', 'post_id', 'post_type' );
}
}
return $posts;
}
Hopefully I am not diluting this thread, but I have a request to the widget "Top post and pages" and this is the option to exclude (not show in the list) certain posts by their id. Possible?
@chjan You can use the jetpack_widget_get_top_posts filter to do that. You can check the documentation here:
https://developer.jetpack.com/hooks/jetpack_widget_get_top_posts/