How to Set up a Custom Date Field And Order Posts by This Field’s Value

In one of the recent WordPress customization tasks I took up, the requirement was for the user to be able to enter a date in the format of yyyymmdd (Ex.: 18760310) which should appear below the post titles as: “Friday, Mar 10th, 1876″ plus the posts on the /blog page to be automatically sorted by this date value.

Here’s how I did it.

1) Installed and activated Advanced Custom Fields plugin.

2) Set up the date field (Field Type: Text) in ACF.

2013-03-04 18-11-39

Here is what I entered in ‘Field Instructions’:

Enter date in this format: <strong><span style="color: red;">YYYY</span><span style="color: green;">MM</span><span style="color: blue;">DD</span></strong>

3) Edited Posts and added the custom date field’s values like this: 18760310

2013-03-04 17-49-45

4) Edited theme template files like single.php, index.php and archive.php and used this code wherever the custom date should be displayed:

<?php
	$ref_date = get_field('referendum_date'); 

	if ( !empty($ref_date) ) { echo '<div class="referendum-date"> Referendum Date: ' . date("l, M jS, Y", strtotime("$ref_date")) . '</div>' ; }
?>

to get

2013-03-04 17-54-45

5) To sort the posts by this field’s value in ascending order, added the following above the loop in index.php:

<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts("order=asc&orderby=meta_value&meta_key=referendum_date&paged=$paged"); ?>

Note: Posts with nothing entered for custom date field will not appear on the Posts page.

Comments

Leave a Reply