In our previous lesson we have learnt how to build WordPress plugin from scratch with custom table . Now you want to show the data in front-end. So how to do it? To do that you need to create shortcode WordPress function so that you can use it in your post or page or widget easily. To know more about WordPress short code you can visit resource page Shortcode API. Now we will show you how to create Shortcode in WordPress Plugin.
We are working in our previous plugin how to build WordPress plugin from scratch with custom table. So to understand what we are doing please first learn previous plugin. So now we are going to add shortcode funtion at the end of file mtgplugintest.php
wp_register_style(‘mtgpluginstest-style’, get_bloginfo(‘url’) . ‘/wp-content/plugins/’ . basename(dirname(__FILE__)) . ‘/css/plugin-test.css’);
$tablename = $wpdb->prefix . "mtgpluginstest_table_name";
$retrieve_data = $wpdb->get_results( "SELECT * FROM $tablename ORDER BY table_name_id");
foreach ( $retrieve_data as $data )
$return_data_list.= ‘<div id="block">
<p class="content"><span class="laquo"> </span>’. $data->table_name_title.'<span class="raquo"> </span></br> ‘. $data->table_name_date.'</p>
Here we build a shortcode funtion mtgpluginstest_lists . In line 4 and 5 we have added CSS for the front-end design. Then we have queried all the data from table mtgpluginstest_table_name. One of the most import thing must remember that you have to return the data list. If you simply query the data inside foreach loop, all the shortcode output in the front-end will be shown in front of all other data of that particular page or post. So check the return part from line 11 to 15. Then finally we use add_shorcode WordPress function to build the shortcode in line 17. There are two part in this function. First part is the code we are going to use in a post or page or widget. You can name it whatever you want and we named it as mtg-mtgpluginstest-lists and second part is the function mtgpluginstest_lists we have created.
How to Use Shortcode:
So you have successfully create the shortcode and now we will use that in a page. Suppose in our data list we have two data and we want to show this data in a page:
For example we have a page name Data List and in that page use the short code [mtg-mtgpluginstest-lists]
Save the page and all the data will be shown as follows:
You can download complete plugin from here create shorcode in wordpress plugin and don’t forget to comment if you like the tutorial.