Add shortcode that reads from the database (Youtube tutorial)

This is the source code for a Youtube tutorial I posted on my channel.

Adding front-end code to WordPress is pretty straightforward. 

However, if we need to add code that runs on the server, for accessing the database for example things get more complicated. 

This is because WordPress has a very strict order of executing code when rendering pages. 

One way of adding server code is through short code functions.

In this video we are going to write a short code that reads a list of employees from the databases and displays them in a table.

add_shortcode( 'list-employees', function () {
	ob_start(); ?>
		<table>
			<tr>
				<th>First name</th>
				<th>Last name</th>
			</tr>
	<?php
	global $wpdb;
	$results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}employees LIMIT 100");
	foreach ($results as $row) {
		echo "<tr><td>{$row->first_name}</td><td>{$row->last_name}</td></tr>";
	}
	echo "</table>";

	return ob_get_clean();
} );

Leave a comment

Your email address will not be published. Required fields are marked *