WordPress plugin development tutorial using MySQL

today we will learn how to develop a WordPress plugin using MySQL database table by creating during installation, inserting from WordPress admin panel and fetching value in frontend using the shortcode. and for this plugin, you can be able to get the social media list by using the shortcode [CM_SOCIAL_MEDIA].

now step by step develop the plugin,

First Step:

create a folder inside the plugin directory of your WordPress project and give a name to it as cm_social_media

Second Step:

now create a PHP file as same name as the folder created in our case it will be cm_social_media.php

Third Step:

Now start to write code on cm_social_media.php inside PHP tag and as commenting text to define the theme

Example:

 
<?php
/**
*  Plugin Name: Code Mystery Social Media
*  Description: its a simple social media plugin 
*  Version: 1
*  Author: Code Mystery
*  Author URI: https://www.codemystery.com/
**/
?>

Fourth Step:

Now create a function to be run during installation time and inside that define global wpdb and write the code to create a table

* note must check if the table does not exist already
Example:

function your_plugin_options_install() {
   	global $wpdb;
  	global $cm_social_media_settings;

 	$charset_collate = $wpdb->get_charset_collate();
	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	
	$query = "";
	$cm_social_media_settings = $wpdb->prefix . 'social_media';

	if($wpdb->get_var("show tables like '$cm_social_media_settings'") != $cm_social_media_settings) 
	{

		$query .= "CREATE TABLE IF NOT EXISTS $cm_social_media_settings (
					  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
					  `media_name` varchar(255) NOT NULL DEFAULT '',
					  `media_link` varchar(255) NOT NULL DEFAULT '',
					  `media_icon` varchar(255) NOT NULL DEFAULT '',
					  PRIMARY KEY (`id`)
					) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";

	}

	//dbDelta($sql);
	$myquery_res = $wpdb->get_results( $query );
}
// run the install scripts upon plugin activation
register_activation_hook(__FILE__,'your_plugin_options_install');

Fifth Step:

Now create an admin menu and its submenu and define the functions name to call on click of the links.

Example:

function ad_cm_social_media_menu() {
	//adding main admin menu
	add_menu_page(
					'social_media',   //page title
	              	'Social Media',   //menu title
				  	'manage_options', //capabilities
				  	'social-media',   //menu slug
				  	social_media_list //function to call
				);

	//adding sub admin menu for social media list
    add_submenu_page(
    				'social-media', //parrent slug 
    				'All Social Media', //page title 
    				'All Social Media', //menu title 
    				'manage_options', //capabilities 
    				'all-social-media', //menu slug
    				social_media_list //function to call
    			);

    //adding sub admin menu for add social menia
    add_submenu_page(
    				'social-media', //parrent slug 
    				'Add Social Media', //page title 
    				'Add Social Media', //menu title 
    				'manage_options', //capabilities 
    				'add-social-media', //menu slug
    				add_social_media //function to call
    			);
}
add_action('admin_menu', 'ad_cm_social_media_menu');

*note in this case we need two functions one for a list and another for add the values

Sixth Step:

Declare the function to display the list in the admin panel which is calling from menu declaration

example:

function social_media_list() {
    ?>
    <style>
        table {
            border-collapse: collapse;
        }
        table, td, th {
            border: 1px solid black;
            padding: 20px;
            text-align: center;
        }
    </style>
    <div class="wrap" style="width: 95%; overflow: scroll;">
        <?php if (isset($_GET['data_updated'])&&$_GET['data_updated']=='data_updated') {
            echo "<p style='padding 20px;'>Data Updated</p>";
        } ?>
        <table style="width: 100%;">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Media Name</th>
                    <th>Media Link</th>
                    <th>Media Icon</th>
                    <th>Edit</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $table_name = $wpdb->prefix . "social_media";
                $rows = $wpdb->get_results( "SELECT * FROM $table_name;");
                //var_dump($rows);
                $counter = 0;
                foreach ($rows as $key => $row) {
                $counter += 1;
                ?>
                <tr>
                    <td><?php echo $counter; ?></td>
                    <td><?php echo $row->media_name; ?></td>
                    <td><?php echo $row->media_link; ?></td>
                    <td><?php echo $row->media_icon; ?></td>
                    <td><a href="admin.php?page=add-social-media&edit=edit&idd=<?php echo $row->id; ?>">Edit</a></td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
<?php
}

Seventh Step:

Now define the function to add the values in the MySQL table

example:

function add_social_media(){
   $table_name = $wpdb->prefix . "social_media";
?>
  	<div class="postbox closed" id="<?php echo $_GET['page']; ?>" style="display:table;width:97%;">
		<div class="handlediv" title="Click to Toggle"></div>
		<h3 class="hndle" style="padding: 0px 10px 0px 15px;">
			Social Media
			<?php 
			if (isset($_POST['submit_car_type'])){
				$id = $_POST['id'];
				$media_name = $_POST['media_name'];
				$media_link = $_POST['media_link'];
				$media_icon = $_POST['media_icon'];

				$query_data = array(
								'media_name' => $media_name,
								'media_link' => $media_link,
								'media_icon' => $media_icon
							  );

				$query_data_where = array(
										'id' => $id
									  );

				$updated = '';

				if(isset($_GET['edit']) && $_GET['edit'] == 'edit'){
					echo $updated = $wpdb->update( $table_name, $query_data, $query_data_where );

					if($wpdb->last_error !== '') :
					    $wpdb->print_error();
					endif;
				}else{
					$updated = $wpdb->insert( $table_name, $query_data);
					if($wpdb->last_error !== '') :
					    $wpdb->print_error();
					endif;
				}

				if ($updated) {
					echo "<h3 style='color:green;'>Data successfully updated</h3>";
					echo "<h3 style='color:green;'>Data successfully updated</h3>";
					$url = 'admin.php?page=taxi-booking-car-types&data_updated=data_updated';
					if ( wp_redirect( $url ) ) {
					    exit;
					}
				}else{
					echo "<h3 style='color:red;'>Data not updated please try again</h3>";
				}
			}
			?>
		</h3>
		<div class="inside" style="display: block;">
			<div class="metabox-holder">
				<div class="postbox-container" style="display:table;width:100%;">
      				<div class="meta-box-sortables ui-sortable">
      					<?php 
      					$id = '';
      					$media_name = '';
      					$media_link = '';
      					$media_icon = '';
      					if(isset($_GET['edit']) && $_GET['edit'] == 'edit'){
      						$idd = $_GET['idd'];
	      					$rows = $wpdb->get_results( "SELECT * FROM `$table_name` WHERE `id`='$idd ';"); 
	      					foreach ($rows as $key => $row) {
	      						$id = $row->id;
	      						$media_name = $row->media_name;
		      					$media_link = $row->media_link;
		      					$media_icon = $row->media_icon;
	      					}
	      				}
      					?>

        				<form action="" method="post">
        					<input type="hidden" name="id" value="<?php echo $id; ?>" />
        					<table class="form-table hm-form">
        						<tr>
									<th>
										Social Media Name
									</th>
									<td>
										<input type="text" name="media_name" required="required" value="<?php echo $media_name; ?>" />
									</td>
								</tr>
        						<tr>
									<th>
										Social Media Link
									</th>
									<td>
										<input type="text" name="media_link" required="required" value="<?php echo $media_link; ?>" />
									</td>
								</tr>
        						<tr>
									<th>
										Social Media Icon
									</th>
									<td>
										<input type="text" name="media_icon" required="required" value="<?php echo $media_icon; ?>" />
									</td>
								</tr>
        						<tr>
									<th></th>
									<td>
										<input type="submit" name="submit_car_type" value="Submit" />
									</td>
								</tr>
        					</table>
        				</form> 
        			</div>
      			</div>
    		</div>
		</div>
	</div>
<?php
}

Eight Step:

Now define a shortcode and make functionality to get the values in frontend using the shortcode

Example:

// Add shortcode to get the social media in frontend
add_shortcode("CM_SOCIAL_MEDIA", "cm_social_media_get");

function cm_social_media(
	$output_first_form = cm_social_media_get();
	//send back text to replace shortcode in post
	return $output_first_form;
}

function cm_social_media_get(){

	//to include the fontwasome icon
	wp_enqueue_style( 'style', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css' );


	$table_name = $wpdb->prefix . "social_media";
    $rows = $wpdb->get_results( "SELECT * FROM $table_name;");
    $counter = 0;


    echo '<ul>';
    foreach($rows as $key => $row){
    	echo '<li>';
        	echo '<a href="'.$row->media_link.'" title="'.$row->media_name.'">';
        		echo '<i class="fa '.$row->media_icon.'"></i>';
        	echo '</a>';
    	echo '</li>';
    }
    echo '</ul>';


}

Now here is the full code to create the plugin

<?php
/**
*  Plugin Name: Code Mystery Social Media
*  Description: its a simple social media plugin 
*  Version: 1
*  Author: Code Mystery
*  Author URI: https://www.codemystery.com/
**/

/** get the social link by [CM_SOCIAL_MEDIA] shortcode **/


/************************************************************************/

// function to create the DB / Options / Defaults during the installation
function your_plugin_options_install() {
   	global $wpdb;
  	global $cm_social_media_settings;

 	$charset_collate = $wpdb->get_charset_collate();
	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	
	$query = "";
	$cm_social_media_settings = $wpdb->prefix . 'social_media';

	if($wpdb->get_var("show tables like '$cm_social_media_settings'") != $cm_social_media_settings) 
	{

		$query .= "CREATE TABLE IF NOT EXISTS $cm_social_media_settings (
					  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
					  `media_name` varchar(255) NOT NULL DEFAULT '',
					  `media_link` varchar(255) NOT NULL DEFAULT '',
					  `media_icon` varchar(255) NOT NULL DEFAULT '',
					  PRIMARY KEY (`id`)
					) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";

	}

	//dbDelta($sql);
	$myquery_res = $wpdb->get_results( $query );
}
// run the install scripts upon plugin activation
register_activation_hook(__FILE__,'your_plugin_options_install');

/************************************************************************/

//Creating the admin menu for the plugin
function ad_cm_social_media_menu() {
	//adding main admin menu
	add_menu_page(
					'social_media',   //page title
	              	'Social Media',   //menu title
				  	'manage_options', //capabilities
				  	'social-media',   //menu slug
				  	social_media_list //function to call
				);

	//adding sub admin menu for social media list
    add_submenu_page(
    				'social-media', //parrent slug 
    				'All Social Media', //page title 
    				'All Social Media', //menu title 
    				'manage_options', //capabilities 
    				'all-social-media', //menu slug
    				social_media_list //function to call
    			);

    //adding sub admin menu for add social menia
    add_submenu_page(
    				'social-media', //parrent slug 
    				'Add Social Media', //page title 
    				'Add Social Media', //menu title 
    				'manage_options', //capabilities 
    				'add-social-media', //menu slug
    				add_social_media //function to call
    			);
}
add_action('admin_menu', 'ad_cm_social_media_menu');

/************************************************************************/

// the function for showing the social media list
function social_media_list() {
    ?>
    <style>
        table {
            border-collapse: collapse;
        }
        table, td, th {
            border: 1px solid black;
            padding: 20px;
            text-align: center;
        }
    </style>
    <div class="wrap" style="width: 95%; overflow: scroll;">
        <?php if (isset($_GET['data_updated'])&&$_GET['data_updated']=='data_updated') {
            echo "<p style='padding 20px;'>Data Updated</p>";
        } ?>
        <table style="width: 100%;">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Media Name</th>
                    <th>Media Link</th>
                    <th>Media Icon</th>
                    <th>Edit</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $table_name = $wpdb->prefix . "social_media";
                $rows = $wpdb->get_results( "SELECT * FROM $table_name;");
                //var_dump($rows);
                $counter = 0;
                foreach ($rows as $key => $row) {
                $counter += 1;
                ?>
                <tr>
                    <td><?php echo $counter; ?></td>
                    <td><?php echo $row->media_name; ?></td>
                    <td><?php echo $row->media_link; ?></td>
                    <td><?php echo $row->media_icon; ?></td>
                    <td><a href="admin.php?page=add-social-media&edit=edit&idd=<?php echo $row->id; ?>">Edit</a></td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
<?php
}


/************************************************************************/


// The function for add social media
function add_social_media(){
   $table_name = $wpdb->prefix . "social_media";
?>
  	<div class="postbox closed" id="<?php echo $_GET['page']; ?>" style="display:table;width:97%;">
		<div class="handlediv" title="Click to Toggle"></div>
		<h3 class="hndle" style="padding: 0px 10px 0px 15px;">
			Social Media
			<?php 
			if (isset($_POST['submit_car_type'])){
				$id = $_POST['id'];
				$media_name = $_POST['media_name'];
				$media_link = $_POST['media_link'];
				$media_icon = $_POST['media_icon'];

				$query_data = array(
								'media_name' => $media_name,
								'media_link' => $media_link,
								'media_icon' => $media_icon
							  );

				$query_data_where = array(
										'id' => $id
									  );

				$updated = '';

				if(isset($_GET['edit']) && $_GET['edit'] == 'edit'){
					echo $updated = $wpdb->update( $table_name, $query_data, $query_data_where );

					if($wpdb->last_error !== '') :
					    $wpdb->print_error();
					endif;
				}else{
					$updated = $wpdb->insert( $table_name, $query_data);
					if($wpdb->last_error !== '') :
					    $wpdb->print_error();
					endif;
				}

				if ($updated) {
					echo "<h3 style='color:green;'>Data successfully updated</h3>";
					echo "<h3 style='color:green;'>Data successfully updated</h3>";
					$url = 'admin.php?page=taxi-booking-car-types&data_updated=data_updated';
					if ( wp_redirect( $url ) ) {
					    exit;
					}
				}else{
					echo "<h3 style='color:red;'>Data not updated please try again</h3>";
				}
			}
			?>
		</h3>
		<div class="inside" style="display: block;">
			<div class="metabox-holder">
				<div class="postbox-container" style="display:table;width:100%;">
      				<div class="meta-box-sortables ui-sortable">
      					<?php 
      					$id = '';
      					$media_name = '';
      					$media_link = '';
      					$media_icon = '';
      					if(isset($_GET['edit']) && $_GET['edit'] == 'edit'){
      						$idd = $_GET['idd'];
	      					$rows = $wpdb->get_results( "SELECT * FROM `$table_name` WHERE `id`='$idd ';"); 
	      					foreach ($rows as $key => $row) {
	      						$id = $row->id;
	      						$media_name = $row->media_name;
		      					$media_link = $row->media_link;
		      					$media_icon = $row->media_icon;
	      					}
	      				}
      					?>

        				<form action="" method="post">
        					<input type="hidden" name="id" value="<?php echo $id; ?>" />
        					<table class="form-table hm-form">
        						<tr>
									<th>
										Social Media Name
									</th>
									<td>
										<input type="text" name="media_name" required="required" value="<?php echo $media_name; ?>" />
									</td>
								</tr>
        						<tr>
									<th>
										Social Media Link
									</th>
									<td>
										<input type="text" name="media_link" required="required" value="<?php echo $media_link; ?>" />
									</td>
								</tr>
        						<tr>
									<th>
										Social Media Icon
									</th>
									<td>
										<input type="text" name="media_icon" required="required" value="<?php echo $media_icon; ?>" />
									</td>
								</tr>
        						<tr>
									<th></th>
									<td>
										<input type="submit" name="submit_car_type" value="Submit" />
									</td>
								</tr>
        					</table>
        				</form> 
        			</div>
      			</div>
    		</div>
		</div>
	</div>
<?php
}


/************************************************************************/


// Add shortcode to get the social media in frontend
add_shortcode("CM_SOCIAL_MEDIA", "cm_social_media_get");

function cm_social_media(
	$output_first_form = cm_social_media_get();
	//send back text to replace shortcode in post
	return $output_first_form;
}

function cm_social_media_get(){

	//to include the fontwasome icon
	wp_enqueue_style( 'style', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css' );


	$table_name = $wpdb->prefix . "social_media";
    $rows = $wpdb->get_results( "SELECT * FROM $table_name;");
    $counter = 0;


    echo '<ul>';
    foreach($rows as $key => $row){
    	echo '<li>';
        	echo '<a href="'.$row->media_link.'" title="'.$row->media_name.'">';
        		echo '<i class="fa '.$row->media_icon.'"></i>';
        	echo '</a>';
    	echo '</li>';
    }
    echo '</ul>';


}

Now the plugin is ready to install and configure and you can be able to get the value in frontend using the shortcode [CM_SOCIAL_MEDIA]

Thanks for reading and please give your valuable comment to make the site better.

Share The Post On -