-
Notifications
You must be signed in to change notification settings - Fork 83
3. Filters
Filter hooks are one of the most versatile and useful features that WordPress has to offer. It allows maximum flexibility when it comes to modifying stuff, be it a theme, a plugin and even WordPress itself.
WordPress Popular Posts takes advantage of this to let you modify the plugin (HTML output, plugin behavior, etcetera) so it matches your specific needs. To use these filters, put them in your theme's functions.php file (or in a site-specific plugin).
Here's a list of available filter hooks as of WordPress Popular Posts 5.4.2. The list is not definitive nor all of the hooks have been documented here yet so check back regularly for more details.
Since: 5.0.0
This hooks allows you to register one or more themes for the widget (see developing a custom theme for more details).
Parameters:
-
$themes
- An array of theme paths.
Usage example:
/**
* Registers my WPP theme.
*
* @param array $themes
* @return array
*/
function wpp_register_my_wpp_theme($themes) {
// Absolute path to the theme
$themes[] = plugin_dir_path(__FILE__) . 'my-theme'; // Use get_template_directory() instead if your WPP theme is inside a WordPress theme directory.
return $themes;
}
add_filter('wpp_additional_themes', 'wpp_register_my_wpp_theme', 10, 1);
Since: 5.0.0.
Extends the CSS rules of the currently applied theme.
Parameters:
-
$additional_styles
- Additional CSS rules. -
$theme_name
- Theme name.
Usage example:
/**
* Make popular posts links red in 'Cards' theme.
*
* @param string $additional_styles
* @param string $theme_name
* @return string
*/
function wpp_additional_css_rules($additional_styles, $theme_name) {
if ( 'cards' == $theme_name ) {
$additional_styles .= '.wpp-list li a { color: red; }';
}
return $additional_styles;
}
add_filter('wpp_additional_theme_styles', 'wpp_additional_css_rules', 10, 2);
Make sure you change cards
to the folder name of the WPP theme you're using (eg. 'cards-compact', 'tiny', etc.)
Since: 5.4.1.
Allows to disable WPP's Block editor support entirely.
Parameters:
-
$block_editor_support
, boolean. Defaults totrue
.
Usage example:
/**
* Disables WPP's Block Editor support.
*/
add_filter('wpp_block_editor_support', '__return_false');
Since: 7.0.0.
With wpp_custom_html you get full control of the HTML output of the headline of your popular posts list.
Parameters:
-
$header_html
- string, the HTML for the headline. -
$options
- an array of options from the block/shortcode/template tag.
Usage example:
/**
* Modifies the HTML markup of the popular posts list headline.
*
* @param string $header_html
* @param array $options
* @return string
*/
function my_12345_wpp_header_html($header_html, $options) {
return '<div class="my-custom-class">' . $options['title'] . '</div>';
}
add_filter('wpp_custom_header_html', 'my_12345_wpp_header_html', 10, 2);
Since: 3.0.0.
With wpp_custom_html you get full control of the HTML output.
Parameters:
-
$popular_posts
- an array of popular posts objects. -
$instance
- an array of options from the widget/shortcode/template tag.
Keep in mind that the data you'll receive depends on what options you have enabled/disabled in the widget/shortcode/template tag.
Usage example:
/**
* Builds custom HTML.
*
* With this function, I can alter WPP's HTML output from my theme's functions.php.
* This way, the modification is permanent even if the plugin gets updated.
*
* @param array $popular_posts
* @param array $instance
* @return string
*/
function my_custom_popular_posts_html_list($popular_posts, $instance) {
$output = '<ol class="wpp-list">';
// loop the array of popular posts objects
foreach( $popular_posts as $popular_post ) {
$stats = array(); // placeholder for the stats tag
// Comment count option active, display comments
if ( $instance['stats_tag']['comment_count'] ) {
// display text in singular or plural, according to comments count
$stats[] = '<span class="wpp-comments">' . sprintf(
_n('1 comment', '%s comments', $popular_post->comment_count, 'wordpress-popular-posts'),
number_format_i18n($popular_post->comment_count)
) . '</span>';
}
// Pageviews option checked, display views
if ( $instance['stats_tag']['views'] ) {
// If sorting posts by average views
if ($instance['order_by'] == 'avg') {
// display text in singular or plural, according to views count
$stats[] = '<span class="wpp-views">' . sprintf(
_n('1 view per day', '%s views per day', intval($popular_post->pageviews), 'wordpress-popular-posts'),
number_format_i18n($popular_post->pageviews, 2)
) . '</span>';
} else { // Sorting posts by views
// display text in singular or plural, according to views count
$stats[] = '<span class="wpp-views">' . sprintf(
_n('1 view', '%s views', intval($popular_post->pageviews), 'wordpress-popular-posts'),
number_format_i18n($popular_post->pageviews)
) . '</span>';
}
}
// Author option checked
if ( $instance['stats_tag']['author'] ) {
$author = get_the_author_meta('display_name', $popular_post->uid);
$display_name = '<a href="' . get_author_posts_url($popular_post->uid) . '">' . $author . '</a>';
$stats[] = '<span class="wpp-author">' . sprintf(__('by %s', 'wordpress-popular-posts'), $display_name). '</span>';
}
// Date option checked
if ( $instance['stats_tag']['date']['active'] ) {
$date = date_i18n($instance['stats_tag']['date']['format'], strtotime($popular_post->date));
$stats[] = '<span class="wpp-date">' . sprintf(__('posted on %s', 'wordpress-popular-posts'), $date) . '</span>';
}
// Category option checked
if ( $instance['stats_tag']['category'] ) {
$post_cat = get_the_category($popular_post->id);
$post_cat = ( isset($post_cat[0]) )
? '<a href="' . get_category_link($post_cat[0]->term_id) . '">' . $post_cat[0]->cat_name . '</a>'
: '';
if ( $post_cat != '' ) {
$stats[] = '<span class="wpp-category">' . sprintf(__('under %s', 'wordpress-popular-posts'), $post_cat) . '</span>';
}
}
// Build stats tag
if ( ! empty($stats) ) {
$stats = '<div class="wpp-stats">' . join(' | ', $stats) . '</div>';
} else {
$stats = null;
}
$excerpt = ''; // Excerpt placeholder
// Excerpt option checked, build excerpt tag
if ( $instance['post-excerpt']['active'] ) {
$excerpt = get_excerpt_by_id($popular_post->id);
if ( ! empty($excerpt) ) {
$excerpt = '<div class="wpp-excerpt">' . $excerpt . '</div>';
}
}
$output .= "<li>";
$output .= "<h2 class=\"entry-title\"><a href=\"" . get_permalink($popular_post->id) . "\" title=\"" . esc_attr($popular_post->title) . "\">" . $popular_post->title . "</a></h2>";
$output .= $stats;
$output .= $excerpt;
$output .= "</li>" . "\n";
}
$output .= '</ol>';
return $output;
}
add_filter('wpp_custom_html', 'my_custom_popular_posts_html_list', 10, 2);
/**
* Gets the excerpt using the post ID outside the loop.
*
* @author Withers David
* @link http://uplifted.net/programming/wordpress-get-the-excerpt-automatically-using-the-post-id-outside-of-the-loop/
* @param int $post_id
* @return string
*/
function get_excerpt_by_id($post_id) {
// Get post data
$the_post = get_post($post_id);
// Get post_content
$the_excerpt = $the_post->post_content;
// Set excerpt length to 35 words, feel free to change this to whatever you like
$excerpt_length = 35;
// Remove all HTML tags
$the_excerpt = strip_tags(strip_shortcodes($the_excerpt));
$words = explode(' ', $the_excerpt, $excerpt_length + 1);
if ( count($words) > $excerpt_length ) :
array_pop($words);
array_push($words, '...');
$the_excerpt = implode(' ', $words);
endif;
$the_excerpt = '<p>' . $the_excerpt . '</p>';
return $the_excerpt;
}
Since: 5.0.0.
Changes the fallback "No Thumbnail" image URL.
Parameters:
-
$img_url
- a string, the "No Thumbnail" image URL. -
$post_id
- an integer, the post/page ID.
Usage example:
/**
* Renders an alternative thumbnail from a custom field
* if the post doesn't have a thumbnail.
*
* @param string $img_url The default 'No thumbnail' image URL
* @param int $post_id The post/page ID
* @return string $img_url The (modified) 'No thumbnail' image URL
*/
function wpp_custom_field_thumbnail_fallback( $img_url, $post_id ) {
// Post doesn't have a thumbnail so let's fallback
// to the custom field one
//
// Get the image URL from your custom field here
// and then assign it to $img_url or return your URL
//
// eg. $img_url = get_post_meta( $post_id, 'MY_CUSTOM_FIELD_IMG_URL', true );
return $img_url;
}
add_filter( 'wpp_default_thumbnail_url', 'wpp_custom_field_thumbnail_fallback', 10, 2 );
Since: 4.2.1.
Changes the ending string (an ellipsis by default) of the excerpts produced by WPP.
Parameters:
-
$more
- a string.
Usage example:
/**
* Changes the ending string of the excerpt.
*
* @param string $more
* @return string
*/
function my_wpp_excerpt_more($more) {
return '[...]';
}
add_filter('wpp_excerpt_more', 'my_wpp_excerpt_more', 10, 1);
Since: 3.3.0.
The wpp_no_data filter is used to filter the HTML output when WPP is unable to find popular posts (in other words, gives you the ability to change the "Sorry. No data so far." message).
Parameters
-
$no_data_html
- the original "Sorry, no data so far" message.
Usage example:
/**
* Change WPP's 'Sorry. No data so far.' message.
*
* @param string $no_data_html
* @return string
*/
function my_custom_no_posts_found($no_data_html) {
$output = '<p>Um, err... Nothing to see here, move along!</p>';
return $output;
}
add_filter('wpp_no_data', 'my_custom_no_posts_found', 10, 1);
Since: 4.2.0
Use this filter to add new Content Tags for use in WPP's custom HTML markup options (except when using the wpp_custom_html
or the wpp_post
filter hooks).
Parameters:
-
$html
- the parsed HTML string. -
$post_id
- the post/page ID.
Usage example:
/**
* Parses custom content tags in WordPress Popular Posts.
*
* @param string $html The HTML markup from the plugin.
* @param integer $post_id The post/page ID.
* @return string
*/
function wpp_parse_tags_in_popular_posts($html, $post_id) {
// Replace custom content tag {tags} with actual tags
if ( false !== strpos($html, '{tags}') ) {
// Get tags
$tags = get_the_tags($post_id);
$tag_links = '<small>Tags: ';
if ( $tags ) {
foreach( $tags as $tag ) {
$tag_links .= '<a href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a>, ';
}
// Remove last comma from tags list
$tag_links = rtrim($tag_links, ', ');
// Replace {tags} with the actual tags
$html = str_replace('{tags}', $tag_links, $html);
$html .= '</small>';
}
}
return $html;
}
add_filter('wpp_parse_custom_content_tags', 'wpp_parse_tags_in_popular_posts', 10, 2);
Since: 3.0.0.
Unlike wpp_custom_html, this filter only changes the output of each single post (instead of the entire list).
Parameters:
-
$post_html
- the original single post HTML output (just in case you only need to append extra markup to the original one). -
$popular_post*
- the single post object. -
$instance*
- an array of options from the widget/shortcode/template tag.
Keep in mind that the data you'll receive depends on what options you have enabled/disabled in the widget/shortcode/template tag.
Usage example:
/**
* Display the title and the publish date
*
* @param string $post_html
* @param object $popular_post
* @param array $instance
* @return string
*/
function my_custom_single_popular_post($post_html, $popular_post, $instance) {
$output = '<li><a href="' . get_permalink($popular_post->id) . '" class="my-custom-title-class" title="' . esc_attr($popular_post->title) . '">' . $popular_post->title . '</a> <div class="my-custom-date-class">' . date( 'Y-m-d', strtotime($popular_post->date) ) . '</div></li>';
return $output;
}
add_filter('wpp_post', 'my_custom_single_popular_post', 10, 3);
Since: 5.3.0
Allows to change the separator used when displaying post meta (views count, category, date, author, etc.)
Parameters:
-
$separator
- The string used as separator (default: | )
Usage example:
/**
* Replace WPP's separator with a dash.
*
* @param string $separator
* @return string
*/
function my_wpp_post_meta_separator($separator) {
return ' - ';
}
add_filter('wpp_post_meta_separator', 'my_wpp_post_meta_separator', 10, 1);
Since: 5.1.0
Allows to filter the terms displayed by WordPress Popular Posts (categories, tags, etc) for each popular post. Useful if for example you assign multiple categories to your posts but want WPP to display only one of them.
Parameters:
-
$terms
- An array of post terms (categories, tags, etc.)
Usage example:
/**
* Have WordPress Popular Posts display only one category.
*
* @param array $terms
* @return array
*/
function wpp_display_only_one_category($terms) {
return array_slice($terms, 0, 1);
}
add_filter('wpp_post_terms', 'wpp_display_only_one_category', 10, 1);
Tells WordPress Popular Posts whether to prettify numbers or not.
Since: 5.2.0
Parameters:
-
$prettify_numbers
- A boolean value, default is true.
Usage example:
/**
* Disables WordPress Popular Posts' "Pretty Numbers".
*
* @param bool $pretty_numbers
* @return bool
*/
add_filter('wpp_pretiffy_numbers', '__return_false');
Since: 3.2.2
This filter hook allows you to modify the <img />
tag returned by the plugin.
Parameters:
-
$img_tag
, the HTML<img />
tag -
$post_id
, the post ID
Usage example:
/**
* Adds the nopin attribute to the list of
* allowed IMG attributes.
*
* @see https://help.pinterest.com/en/business/article/prevent-saves-to-pinterest-from-your-site
* @see https://developer.wordpress.org/reference/hooks/wp_kses_allowed_html/
* @param array $tags Array of allowed elements and their attributes
* @param string $context Context under which wp_kses is operating
* @return array $tags The (modified) array
*/
function wpp_allow_nopin_attribute_in_images( $tags, $context ) {
$tags['img']['nopin'] = true;
return $tags;
}
add_filter('wp_kses_allowed_html', 'wpp_allow_nopin_attribute_in_images', 20, 2);
/**
* Adds nopin attribute to WPP's thumbnails.
*
* @param string $img The HTML img tag
* @param int $post_id The post ID
* @return string $img The (modified) HTML img tag
*/
function wpp_add_nopin_to_thumbnail($img, $post_id) {
return str_replace(' src', ' nopin="nopin" src', $img);
}
add_filter('wpp_render_image', 'wpp_add_nopin_to_thumbnail', 10, 2);
Since: 5.3.0
This filter hook allows you to enable/disable WPP's retina display support.
Parameters:
-
$enabled
, a boolean (default: true).
Usage example:
/**
* Disables WPP's retina display support.
*
* @param bool $enabled
* @return bool Whether retina display support is enabled or not
*/
function disable_wpp_retina_support($enabled) {
return false;
}
add_filter('wpp_retina_support', 'disable_wpp_retina_support', 10, 1);
Since: 4.2.0
By default, WordPress Popular Posts displays taxonomies (categories, tags, etc) separated by comma. You can change this behavior by using this hook and replace the comma character with something else.
Parameters:
-
$taxonomy_separator
- the original taxonomy separator (", ")
Usage example:
/**
* Replaces the comma separator with a slash.
*
* @param string $separator
* @return string
*/
function wpp_custom_taxonomy_separator($separator) {
return " / ";
}
add_filter('wpp_taxonomy_separator', 'wpp_custom_taxonomy_separator', 10, 1);
Since: 5.0.0
This hook allows you to customize the post title.
Parameters:
-
$title
- The original post title. -
$post_id
- The post ID. -
$translation_post_id
- The post ID of the translated version (when using WPML or Polylang).
Usage example:
/**
* Modifies the post title.
*
* @param string $title
* @param int $post_id
* @param int $translation_post_id
* @return string
*/
function wpp_change_post_title($title, $post_id, $translation_post_id) {
// Do your changes to the title here
// and when you're done...
return $title;
}
add_filter('wpp_the_title', 'wpp_change_post_title', 10, 3);
Since: 6.1.0
Allows to modify the post date.
Parameters:
-
$post_date
- a string containing the post date. -
$post_id
- integer, the post ID.
Usage example:
/**
* Renders the modified date of a popular post instead of its publication date.
*
* @param string $post_date
* @param int $post_id
* @return string
*/
function my_wpp_render_modified_date($post_date, $post_id) {
return get_the_modified_time('d.M Y', $post_id);
}
add_filter('wpp_the_date', 'my_wpp_render_modified_date', 10, 2);
Since: 5.0.0
Allows to modify the ALT attribute of the thumbnail.
Parameters:
-
$alt_attribute
- a string containing the original ALT attribute. -
$post_id
- integer, the post ID.
Usage example:
/**
* Modifies WPP thumbnails' ALT attribute.
*
* @param string $alt_attribute
* @param int $post_id
* @return string
*/
function my_wpp_thumbnail_alt_attribute($alt_attribute, $post_id) {
if ( empty($alt_attribute) ) {
// Let's use the post title as ALT attribute
// for our thumbnail
$alt_attribute = get_post_field('post_title', $post_id);
}
return $alt_attribute;
}
add_filter('wpp_thumbnail_alt_attribute', 'my_wpp_thumbnail_alt_attribute', 10, 2);
Since: 5.0.0
Allows to modify the CSS class attribute of the thumbnails.
Parameters:
-
$classes
- an array of strings containing the CSS classes to be assigned to the thumbnail. -
$post_id
- integer, the post ID.
Usage example:
/**
* Adds a CSS class to WPP's thumbnails.
*
* @param array $classes
* @param int $post_id
* @return array
*/
function my_wpp_thumbnail_css_classes($classes, $post_id) {
$classes[] = 'my-custom-class';
return $classes;
}
add_filter('wpp_thumbnail_class_attribute', 'my_wpp_thumbnail_css_classes', 10, 2);
Since: 4.2.1.
Changes the image compression quality of WPP's thumbnails.
Parameters:
-
$quality
- an integer value ranging from 0 to 100 (eg. 85)
Usage example:
/**
* Sets WPP thumbnail's image quality to 85.
*
* @param int $quality
* @return int
*/
function my_wpp_thumbnail_compression_quality($quality) {
return 85;
}
add_filter('wpp_thumbnail_compression_quality', 'my_wpp_thumbnail_compression_quality', 10, 1);
Since: 3.3.3.
By default, WordPress Popular Posts tracks page views of all public post types. You can change this behavior by using the wpp_trackable_post_types filter to tell WPP which post types should be tracked.
Parameters:
-
$post_types
- an array of post types (eg.['post', 'page']
)
Usage example:
/**
* Have WPP track only 'post' and 'review' post types page views, ignore the rest.
*
* @param array $post_types
* @return array
*/
function my_trackable_post_types($post_types) {
$post_types = array('post', 'review');
return $post_types;
}
add_filter('wpp_trackable_post_types', 'my_trackable_post_types', 10, 1);
Changes the views count value before saving it to the database.
Parameters:
-
$views
- integer, the views count -
$post_ID
- integer, the post/page ID -
$sampling
- integer, whether data sampling is disabled (0) or enabled (1) -
$sampling_rate
- integer, the sampling rate value
Usage example:
/**
* Have WPP multiply views count by 4.
*
* @param integer $views
* @param integer $post_ID
* @param integer $sampling
* @param integer $sampling_rate
* @return integer $views
*/
function wpp_multiply_views_count_by_four($views, $post_ID, $sampling, $sampling_rate) {
return 4;
}
add_filter('wpp_update_views_count_value', 'wpp_multiply_views_count_by_four', 10, 4);