WordPress: Post Table Shortcode

Need to create a list of all the posts on your blog?
Add this shortcode to your worpress theme and you are ready to go!

The Code

Add the following code to your functions.php.

/**************************************************************************************
 * Shorcode function for creating a table containing posts
 *
 * @param attr settings for the worpress method get_posts()
 *        Retrieves all posts by default.
 *************************************************************************************/
function my_posttable($atts) { 
	$attributes = shortcode_atts( array(
		'numberposts' => -1, //retrieve all
		'category' => 0, 
		'orderby' => 'date',
		'order' => 'DESC', 
		'include' => array(),
		'exclude' => array(), 
		'meta_key' => '',
		'meta_value' =>'', 
		'post_type' => 'post',
		'suppress_filters' => true
	), $atts );
			 
	$latest_posts = get_posts( $attributes );

	$htmlTable = '<table id="posttable" class="table table-striped table-responsive">';
		$htmlTable .= '<thead>';
		$htmlTable .= '  <th>';
		$htmlTable .= '     Date';
		$htmlTable .= '  </th>';
		$htmlTable .= '  <th>';
		$htmlTable .= '     Post';
		$htmlTable .= '  </th>';
		$htmlTable .= '  <th>';
		$htmlTable .= '     Tags';
		$htmlTable .= '  </th>';
		$htmlTable .= '</thead>'. "\n";
		
	foreach ( $latest_posts as $current ) {
		
		$htmlTable .= '<tr>';
		$htmlTable .= '  <td>';
		$htmlTable .=       $current->post_date ;
		$htmlTable .= '  </td>';
		$htmlTable .= '  <td>';
		$htmlTable .= '     <a href="' . get_permalink($current) . '">' . $current->post_title . '</a>';
		$htmlTable .= '  </td>';
		
		$htmlTable .= '  <td>';
		
			$posttags = get_the_tags($current->ID);
			if ($posttags) {
				foreach($posttags as $tag) {
					$tag_link = get_tag_link( $tag->term_id );
					$htmlTable .=  '<a class="badge badge-info m-1" href="' . $tag_link . '">' . $tag->name . '</a>';
				}
			}
		$htmlTable .= '  </td>';
		
		$htmlTable .= '</tr>'. "\n";
	}
	$htmlTable .= '</table>';
			 
	return $htmlTable;
}
add_shortcode( 'posttable', 'my_posttable' );	

Using the Shortcode

Add the shortcode to your editor. For example, the following retrieves the latest 5 posts:

[posttable numberposts="5"]

Example Result

Date Post Tags
2023-09-20 20:22:15 List of Funny Random Job Titles creamfunnyjoblistrandomtiramisutitleswhisperer
2021-12-25 08:49:23 List of Free Song Cover / Youtube Thumbnail Images abstractcc0covercreativecommonsfantasyfreeimagelistmusicsongthumbnailvideoyoutube
2021-09-28 12:34:29 Creative Issue Resolved Messages creativitydevelopmentITlist
2021-06-13 07:10:42 Changing Color of a PNG Image adjustchangecolorgimppng
2021-05-31 17:46:34 Speed up your Design Workflow actionsautomationdesignincomekeyboard shortcutsknowledgelearningmacrosoptimizationoptimizephotoshopproductivityrecombinescriptingspeedworkflow

Share:


developmentpostshortcodetablethemewordpress

Leave a Reply

Your email address will not be published.