tutorial101 is the one place for high quality web development, Web Design and software development tutorials and Resources programming. Learn cutting edge techniques in web development, design and software development, download source components and participate in the community.
How to create wodpress plugins and shortcodes 11 example from simple to complex
List of tutorial
1. How to create contact form with submit mail
2. How to insert record post database table
3. How to insert shortcode google ads
4. How to list recent post
5. How to list recent post in shortcode parameters
6. How to list recent post in content shortcode
7. How to enabling shortcodes in widgets
8. Display wordpress menu in shortcode
9. How to insert A Google Maps shortcode
10. How to embed pdf
11. How to Displaying database table data in shortcodes
A standard header is introduced below to establish your plugin’s presence.
<?php
/**
* Plugin Name: My Plugin Name
* Plugin URI: http://mypluginuri.com/
* Description: A brief description about your plugin.
* Version: 1.0 or whatever version of the plugin (pretty self explanatory)
* Author: Plugin Author's Name
* Author URI: Author's website
* License: A "Slug" license name e.g. GPL12
*/
Create folder under plugins folder wp-content\plugins\myplugins_with_shortcode folder name myplugins_with_shortcode and create php file index.php file
2. Add the code below wp-content\plugins\myplugins_with_shortcode\index.php
<?php
/**
* Plugin Name: Custom Plugins with shortcode
* Plugin URI: https://tutorial101.blogspot.com/
* Description: A custom plugin and shortcode for example.
* Version: 1.0
* Author: Cairocoders
* Author URI: http://tutorial101.blogspot.com/
**/
//first example how to create contact form with submit mail
function form_creation(){
//add submit
if (isset( $_POST['cmdsubmit'])) {
$txtname = $_POST['txtname'];
$txtemail = $_POST['txtemail'];
$message = $_POST['message'];
$msg = "Name: $txtname <br/>Email: $txtemail <br/>Message: $message <br/>";
// send email
mail("someone@example.com","My subject",$msg);
}
$form .= '<div class="well"><p><h5>Simple Contact Form</h5></p><form method = "post">
Name: <input type="text" name="txtname" class="form-control"><br>
Email: <input type="email" name="txtemail" class="form-control"><br>
Message: <textarea name="message" class="form-control"> Enter text here…</textarea><br/>
<input type="submit" name="cmdsubmit"> '.$msg.'
</form></div>';
return "$form";
}
add_shortcode("testform", "form_creation"); //add code //<p>[testform]</p>
//add css file
function wpse_89494_enqueue_scripts() {
wp_enqueue_style('handlecss', plugin_dir_url(__FILE__) . 'css/ajaxshortcodestyle.css');
}
//second example how to insert to post
function input_fields( $atts ) {
//add submit
if ( isset( $_POST['gg'] ) ) {
$post = array(
'post_content' => $_POST['content'],
'post_status' => 'publish',
'post_title' => $_POST['title']
);
// Insert the post into the database
wp_insert_post($post); //https://developer.wordpress.org/reference/functions/wp_insert_post/
}
$formpost .= '<form method = "post">
Post title : <input type="text" name="title"><br/>
Post Contents : <input type="text" name="content"></br/>
<input type="submit" name="gg">
</form>';
return "$formpost";
}
add_shortcode( 'add_fields', 'input_fields' );
//third example shortcode google ads
function get_adsense($atts) {
return '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- WordPress hosting -->
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-0327511395451286"
data-ad-slot="6566424785"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>';
}
add_shortcode('adsense', 'get_adsense');
//4th example how to list recent post
function recent_posts_function() {
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string = '<a href="'.get_permalink().'">'.get_the_title().'</a>';
endwhile;
endif;
wp_reset_query();
return $return_string;
}
add_shortcode('recent_posts', 'recent_posts_function');
//5 example SHORTCODE PARAMETERS
function recent_posts_function2($atts){
extract(shortcode_atts(array(
'posts' => 1,
), $atts));
$return_string = '<ul>';
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
endif;
$return_string .= '</ul>';
wp_reset_query();
return $return_string;
}
add_shortcode('recent_posts2', 'recent_posts_function2');
//6 example CONTENT IN SHORTCODE [recent-posts posts="5"]This is the list heading[/recent-posts]
function recent_posts_function3($atts, $content = null) {
extract(shortcode_atts(array(
'posts' => 1,
), $atts));
$return_string = '<h3>'.$content.'</h3>';
$return_string .= '<ul>';
query_posts(array('orderby' => 'date', 'order' => 'DESC' , 'showposts' => $posts));
if (have_posts()) :
while (have_posts()) : the_post();
$return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
endif;
$return_string .= '</ul>';
wp_reset_query();
return $return_string;
}
add_shortcode('recent_posts3', 'recent_posts_function3');
//7 example ENABLING SHORTCODES IN WIDGETS
add_filter('widget_text', 'do_shortcode');
//8 example WORDPRESS MENU
function menu_function($atts, $content = null) {
extract(
shortcode_atts(
array( 'name' => null, ),
$atts
)
);
return wp_nav_menu(
array(
'menu' => $name,
'echo' => false
)
);
}
add_shortcode('menu', 'menu_function');
//9 example A Google Maps shortcode
function googlemap_function($atts, $content = null) {
extract(shortcode_atts(array(
"width" => '640',
"height" => '480',
"src" => ’
), $atts));
return '<iframe width="'.$width.'" height="'.$height.'" src="'.$src.'&output=embed" ></iframe>';
}
add_shortcode("googlemap", "googlemap_function");
//10 example PDF EMBEDDING
function pdf_function($attr, $url) {
extract(shortcode_atts(array(
'width' => '640',
'height' => '480'
), $attr));
return '<iframe src="http://docs.google.com/viewer?url=' . $url . '&embedded=true" style="width:' .$width. '; height:' .$height. ';">Your browser does not support iframes</iframe>';
}
add_shortcode('pdf', 'pdf_function');
// last 11 example Displaying database table data in shortcodes
function listpost_func()
{
global $wpdb;
$postshow .= '<div class="recent-posts">';
$sql_post = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_status='publish'");
foreach ($sql_post as $rows_post)
{
$post_title = $rows_post->post_title;
$postshow .= '<h6>'.$post_title.'</h6>';
}
$postshow .= '</div>';
return "$postshow";
}
add_shortcode( 'listpost', 'listpost_func' );
How To Create A WordPress Plugin
A plugin must contain a bit of meta information which tells WordPress what it is and how to handle it within your website.
A standard header is introduced below to establish your plugin’s presence.
<?php
/**
* Plugin Name: My Plugin Name
* Plugin URI: http://mypluginuri.com/
* Description: A brief description about your plugin.
* Version: 1.0 or whatever version of the plugin (pretty self explanatory)
* Author: Plugin Author's Name
* Author URI: Author's website
* License: A "Slug" license name e.g. GPL12
*/
1 Create folder under plugins folder wp-content\plugins\myplugins folder name myplugins and create index.php file
2. Add the code below
<?php
/**
* Plugin Name: Custom Music Reviews
* Plugin URI: https://tutorial101.blogspot.com/
* Description: A custom music review plugin built for example.
* Version: 1.0
* Author: Cairocoders
* Author URI: http://tutorial101.blogspot.com/
**/
// Register the Custom Music Review Post Type
function register_cpt_music_review() {
$labels = array(
'name' => _x( 'Music Reviews', 'music_review' ), //post type is called music_review url https://codex.wordpress.org/Post_Types
'singular_name' => _x( 'Music Review', 'music_review' ),
'add_new' => _x( 'Add New', 'music_review' ), //and new link wp-admin/post-new.php?post_type=music_review
'add_new_item' => _x( 'Add New Music Review', 'music_review' ),
'edit_item' => _x( 'Edit Music Review', 'music_review' ),
'new_item' => _x( 'New Music Review', 'music_review' ),
'view_item' => _x( 'View Music Review', 'music_review' ),
'search_items' => _x( 'Search Music Reviews', 'music_review' ),
'not_found' => _x( 'No music reviews found', 'music_review' ),
'not_found_in_trash' => _x( 'No music reviews found in Trash', 'music_review' ),
'parent_item_colon' => _x( 'Parent Music Review:', 'music_review' ),
'menu_name' => _x( 'Music Reviews', 'music_review' ), //left side menu edit.php?post_type=music_review
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'description' => 'Music reviews filterable by genre',
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'page-attributes' ),
'taxonomies' => array( 'genres' ),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-format-audio',
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => true,
'capability_type' => 'post'
);
register_post_type( 'music_review', $args );
}
add_action( 'init', 'register_cpt_music_review' );
//custom taxonomies to extend themes or plugins
//Register a new Taxonomy using register_taxonomy()
function genres_taxonomy() { //taxonomy is a way to group things together.
register_taxonomy( //https://codex.wordpress.org/Taxonomies
'genres', //new taxonomy called genres
'music_review', //and assigns it to our post type music_review
array(
'hierarchical' => true,
'label' => 'Genres', //edit-tags.php?taxonomy=genres&post_type=music_review
'query_var' => true,
'rewrite' => array(
'slug' => 'genre',
'with_front' => false
)
)
);
}
add_action( 'init', 'genres_taxonomy');
// Function used to automatically create Music Reviews page.
function create_music_review_pages()
{
//post status and options
$post = array(
'comment_status' => 'open',
'ping_status' => 'closed' ,
'post_date' => date('Y-m-d H:i:s'),
'post_name' => 'music_review',
'post_status' => 'publish' ,
'post_title' => 'Music Reviews',
'post_type' => 'page',
);
//insert page and save the id
$newvalue = wp_insert_post( $post, false );
//save the id in the database
update_option( 'mrpage', $newvalue );
}
// Activates function if plugin is activated
register_activation_hook( __FILE__, 'create_music_review_pages');
//Testing
//first create a new page called "Music Reviews" http://localhost/wordpress/music_review/
//Lets create an example music review and see what outputs.
WordPress – Adding custom fields to the post
This extra custom fields data is known as meta-data. Meta data allow you to add some additional data to the post.
Edit current theme's functions.php below code
/*
* Add the Custom Meta Box
*/
function add_custom_meta_box() {
add_meta_box(
'custom_meta_box', // $id
'Custom Meta Box', // $title
'show_custom_meta_box', // $callback
'post', // $page
'normal', // $context
'high' // $priority
);
}
add_action('add_meta_boxes', 'add_custom_meta_box');
// Custom meta fields array
$prefix = 'custom_';
$custom_meta_fields = array(
array(
'label'=> 'Author Name',
'desc' => 'Enter post author name to be displayed',
'id' => $prefix.'author_name',
'type' => 'text',
),
array(
'label'=> 'Photo',
'desc' => 'Enter url author photo',
'id' => $prefix.'photo_author',
'type' => 'text'
)
);
// The callback function
function show_custom_meta_box() {
global $custom_meta_fields, $post;
// Use nonce for verification
echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
// Begin the field table and loop
echo '<table class="form-table">';
foreach ($custom_meta_fields as $field) {
// get value of this field if it exists for this post
$meta = get_post_meta($post->ID, $field['id'], true);
// begin a table row with
echo '<tr>
<th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
<td>';
switch($field['type']) {
// text field
case 'text':
echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="30" />
<br /><span class="description">'.$field['desc'].'</span>';
break;
nbsp; }
echo '</td></tr>';
}
echo '</table>';
}
// Save the custom meta data
function save_custom_meta($post_id) {
global $custom_meta_fields;
// verify nonce
if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__)))
return $post_id;
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
// check permissions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id))
return $post_id;
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
// loop through fields and save the data
foreach ($custom_meta_fields as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
}
}
add_action('save_post', 'save_custom_meta');
Go to the post adding page and you can see the custom meta box and custom post fields under the post content editor.
Display the Custom Field Value
Edit current theme's single.php and add this code below
<?php
// Get the post meta data
$meta = get_post_meta( get_the_ID() );
// Get custom meta value
$post_author_name = $meta['custom_author_name'][0];
$post_photo_author = $meta['custom_photo_author'][0];
?>
<p>Author: <?php echo $post_author_name; ?> </p>
<p>Photo: <img src="<?php echo $post_photo_author; ?>"/> </p>
Displaying Number of Comments in your WordPress Blog
<?php $numcomms = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'"); if (0 < $numcomms) $numcomms = number_format($numcomms); echo "There's ".$numcomms." total comments on my blog"; ?>
<div id="div1"> <?php //insert new post // Create post object $my_post = array(); $my_post['post_title'] = 'Hello world'; $my_post['post_content'] = 'This is a sample post'; $my_post['post_status'] = 'published'; $my_post['post_author'] = 7; //the id of the author $my_post['post_category'] = array(10,12); //the id's of the categories
// Insert the post into the database $post_id = wp_insert_post( $my_post ); //store new post id into $post_id
//now add tags to new post $tags = array('html', 'css', 'javascript'); wp_set_object_terms( $post_id, $tags, 'post_tag', true );