Filter posts by Alphabets in wordpress

Once again, we continue going to filter the posts. This time we will “Filter posts by Alphabets in WordPress”. As we have discussed filter many times in the previous posts so we will directly start with the tutorial. To filter the posts by alphabet in WordPress, follow these simple steps:

Step 1:

Add the following code where you want to show the filtered data. You can make a template for that or you can show that data on the homepage of your website. Let’s make a template with the name “dcs_filter_alphabets.php”

<div class="alphabets">
	<?php
	foreach (range('A', 'Z') as $char) { ?>
		<a href="#" class="alpha alpha_<?php echo $char;?>" alpha="<?php echo $char;?>"><?php echo $char; ?></a>  
	<?php } ?>
	<a href="#" class="alpha current_alpha" alpha="11">RESET</a>
	<?php
	$results = $wpdb->get_results( "SELECT * FROM `wp_posts` WHERE post_type='opportunity' AND post_status ='publish'", OBJECT );
	$post=array();
	$arr_tmp = array();
	foreach ($results as $result) 
	{
		$post_id = $result->ID;
		$myStr=strtoupper(get_the_title($post_id));
		$arr_tmp[] = substr($myStr, 0, 1);
	}
	sort($arr_tmp);
	$str = array_unique($arr_tmp);
	GLOBAL $tmp_common_alpha; 
	$tmp_common_alpha =  array();
	foreach ($str as $key1) 
	{
		foreach (range('A', 'Z') as $char) {
			if ($key1==$char)
			{
				$tmp_common_alpha[strtoupper($char)] = "alpha_".strtoupper($char);

			}
		}

	}?>
</div>
<div class="alpha_container"></div>

Step 2:

Our template is ready with the UI. Now we will go ahead toward the jquery and ajax work so that we can call the ajax function to do some filtration so that we can Filter posts by Alphabets. Copy and paste the following code into your footer.php file.

<script type="text/javascript">
	jQuery(document).ready(function(){
		jQuery(".alpha").click(function(event){
			event.preventDefault();
			var ajaxurl11 = '<?php echo admin_url('admin-ajax.php'); ?>';
			alpha = jQuery(this).attr("alpha");
			if (alpha==11) {location.reload();};
			jQuery.ajax({
				url: ajaxurl11, 
				dataType: "html",
				type: "POST",
				data:{
					"selected_alpha" : alpha,
					"action" : "get_posts_by_name"
				},
				success: function(data){
					jQuery(".alpha_container").fadeOut( 100 ,function(){                    
						if (!data){
							jQuery(this).html('<span class="no_opp">Sorry no Opportunities found!</span/>');
						}
						else{
							jQuery(this).html(data);
						}
					}
					).fadeIn( 700 );
				}
			});
		});
	});
</script>
<!-- Ajax End -->

<!--************************* Show only filter data alphabatically  ****************************-->
<script type="text/javascript">
	jQuery(document).ready(function(){
		var arrayFromPHP ='<?php echo json_encode($GLOBALS["tmp_common_alpha"]); ?>';
		var jsonparse=JSON.parse(arrayFromPHP);
		jQuery.each(jsonparse, function (i, elem) {
			var tmp = '.'+elem;
			jQuery(tmp).addClass("current_alpha");
		});
	});
</script>

Note: we have used the document.ready function two times so that you guys can understand that we can use this function as many times as we want inside a single file or template.

Step 3:

As we had called function in our jquery code to Filter posts by Alphabets, so now we have to define that function inside the function.php file:

<?php
add_filter( 'posts_where', 'title_like_posts_where', 10, 2 );
function title_like_posts_where( $where, &$wp_query ) {
	global $wpdb;
	if ( $post_title_like = $wp_query->get( 'post_title_like' ) ) {
		$where .= ' AND ' . $wpdb->posts . '.post_title LIKE '' . esc_sql( $wpdb->esc_like( $post_title_like ) ) . '%'';
	}
	return $where;
}

/***********************************Filter Posts by Title *************************************/

add_action( 'wp_ajax_get_posts_by_name', 'get_posts_by_name' );
add_action( 'wp_ajax_nopriv_get_posts_by_name', 'get_posts_by_name' );
function get_posts_by_name(){
	extract($_POST);
	/* Data Comes from ajax request */
	$alphabet = $selected_alpha;
	$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
	// New query to get all the listing item.
	$listing = new WP_Query( array(
		'post_type'=>'opportunity',
		'post_status'=>'publish',
		'posts_per_page'=>-1, 
		'post_title_like' => $alphabet,
		'order' => 'ASC',
		'orderby'    => array( 'meta_value' => 'DESC','title' => 'ASC' ),
		'meta_query' => array(
			array(
				'key'     => 'opportunity_type',
				'value'   => array(0,1,2),
				'compare' => 'IN',
			),
		)
	));  
	if ( $listing->have_posts() ) : 
		while( $listing->have_posts() ) : $listing->the_post();
			echo $post_id=$listing->post->ID;
		endwhile; 
	else: ?>
		<div class="listing-item">
			<p>Sorry no listing found!</p>
		</div>
	<?php 
	endif; 
	wp_reset_query(); 
}

Continue to filter posts by Alphabets

<?php
add_filter( 'posts_where', 'title_like_posts_where', 10, 2 );
function title_like_posts_where( $where, &$wp_query ) {
	global $wpdb;
	if ( $post_title_like = $wp_query->get( 'post_title_like' ) ) {
		$where .= ' AND ' . $wpdb->posts . '.post_title LIKE '' . esc_sql( $wpdb->esc_like( $post_title_like ) ) . '%'';
	}
	return $where;
}

/***********************************Filter Posts by Title *************************************/

add_action( 'wp_ajax_get_posts_by_name', 'get_posts_by_name' );
add_action( 'wp_ajax_nopriv_get_posts_by_name', 'get_posts_by_name' );
function get_posts_by_name(){
	extract($_POST);
	/* Data Comes from ajax request */
	$alphabet = $selected_alpha;
	$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
	// New query to get all the listing item.
	$listing = new WP_Query( array(
		'post_type'=>'opportunity',
		'post_status'=>'publish',
		'posts_per_page'=>-1, 
		'post_title_like' => $alphabet,
		'order' => 'ASC',
		'orderby'    => array( 'meta_value' => 'DESC','title' => 'ASC' ),
		'meta_query' => array(
			array(
				'key'     => 'opportunity_type',
				'value'   => array(0,1,2),
				'compare' => 'IN',
			),
		)
	));  
	if ( $listing->have_posts() ) : 
		while( $listing->have_posts() ) : $listing->the_post();
			echo $post_id=$listing->post->ID;
		endwhile; 
	else: ?>
		<div class="listing-item">
			<p>Sorry no listing found!</p>
		</div>
	<?php 
	endif; 
	wp_reset_query(); 
}

Step 4:

Till now, we are ready with all the functionality. We have to just give the following styles in the last.

<style>
/* Alphabatic pagination */
a.alpha {
	display: inline-block;
	background: none repeat scroll 0% 0% #B5D7F1;
	color: #FFF;
	padding: 0px 7px 0px;
	font-weight: bold;
	margin-right: 2px;
	margin-top: 9px;
	font-size: 12px;
	pointer-events: none;
	cursor: default;
	border-radius: 3px;
}

.current_alpha{
	background: none repeat scroll 0% 0% #2790DF !important;
	pointer-events: visible !important;
	cursor: pointer !important;
}
</style>

Note: Remove the <style> tag if you are adding this style to the .css file.

Conclusion – Filter posts by Alphabets

The above post was made for the WordPress developers who want to filter posts by Alphabets in WordPress. You can find other posts from the sidebar or find some useful WordPress codes here