Skip to content

Instantly share code, notes, and snippets.

@vienhoang
Created August 11, 2014 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vienhoang/1a74a5ddb6f51d7a8cb7 to your computer and use it in GitHub Desktop.
Save vienhoang/1a74a5ddb6f51d7a8cb7 to your computer and use it in GitHub Desktop.
WordPress: Create custom filter
<?php
/*
Plugin Name: VH Filter
Plugin URI: http://vienhoang.com
Description: Filter the content.
Version: 1.0
Author: Vien Hoang
Author URI: http://vienhoang.com
License: GPL2
*/
// Add filter is use to filter content
add_filter( 'the_title' , ucwords );
// add_filter( 'the_content', function($content) {
// return $content . ' ' . time();
// } );
// add_action( 'wp_footer', function() {
// echo 'Hello footer';
// } );
add_action( 'comment_post', function() {
$email = get_bloginfo( 'admin_email' );
// WP email function
wp_mail(
$email,
'New Comment Posted',
'A new comment has been posted.'
);
} );
add_filter( 'the_content', function( $content ) {
$id = get_the_id();
if ( ! is_singular( 'post' ) ) {
return $content;
}
// Retrieve the terms of the taxonomy that are attached to the post.
$terms = get_the_terms( $id, 'category' );
$cats = array();
// Loop throught the terms array with objects and fetch the category id
foreach ( $terms as $term) {
$cats[] = $term->cat_ID;
}
$loop = new WP_Query(
array(
'post_per_page' => 3,
'category__in' => $cats,
'orderby' => 'rand',
// Not fetch current post
'post__not_in' => array($id)
)
);
if ( $loop->have_posts() ) {
$content .= '
<h2>You Also Might Like.. </h2>
<ul class="related-category-post">';
while( $loop->have_posts() ) {
$loop->the_post();
$content .= '
<li>
<a href="' . get_permalink() .'">' . get_the_title() .'</a>
</li>';
}
$content .= '</ul>';
wp_reset_query();
}
return $content;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment