How To Create Related Post WordPress Plugin

Some weeks ago i need to create releated post for single.php . After some tries and looking idea in the internet . Here is the plugin idea : find related post based on categories where related post based on post date before the post single which become the center

To do that we need function : is_single , wp_get_post_categories , get_posts , and add_filter for the_content to put related post under content.

Some Notes : to get post ID on single just use global $post , get_posts is used get post based on criterias, wp_get_post_categories to get categories of existing post

Because we need to convert post date we need function strtotime and date in Y-m-d format . Ok here is the full code :

<?php
/*
Plugin Name: ZZ Related Post
Plugin URI: http://www.wpamanuke.com
Description: Sample Related Post based on category
Version: 1.0.1po
Author: WPAmaNuke
Author URI: https://wpamanuke.com
*/

// ADD BOTTOM RELATED ARTICLE ON THE POST SINGLE
function zz_related_post() {
   // check if single
   if (is_single()) {
		global $post;
		
		$post_ids = [];
		$prev_post = get_previous_post();
		$next_post = get_next_post();
		$i = 0;
		$post_ids[$i] = $post->ID;
		$i++;
		if ($prev_post) {
			$post_ids[$i] = $prev_post->ID;
			$i++;
		}
		/*
		if ($next_post) {
			$post_ids[$i] = $next_post->ID;
		}
		*/
		
		$a = strtotime($post->post_date . " 0 month");
		$time = date("Y-m-d",$a);
		$cat = wp_get_post_categories($post->ID);
		
		
		$related = get_posts( 
			array( 
				'category__in' => $cat, 
				'numberposts' => 3, 
				'post__not_in' => $post_ids,
				//'meta_key'=>'_thumbnail_id',
				'orderby' => 'DATE',
				'order' => 'DESC',
				'date_query' => array(
					'before' => $time 
				)
			) 
		);
		
		
		if ($related) {
			echo '<div class="zz-related-post">';
			echo '<h3>Related Post</h3>';
			
			foreach( $related as $post ) {
				setup_postdata($post);
				?>
				<div class="zz-related-post_block">
				<article>
					<?php if ( has_post_thumbnail() ) { ?>
						<figure class="zz-related-post_image"> 
							<a class="zz-image-link" href="<?php the_permalink(); ?>" title="">
								<?php the_post_thumbnail( 'medium' ); ?>
							</a>
						</figure>
					<?php } ?>
					<div class="zz-related-post_title">
						<h4 class="zz-meta-title"><a href="<?php the_permalink(); ?>" title=""><?php the_title(); ?></a></h4>
					</div>
				</article>    
				</div>
				<?php
			}
			echo '</div>';
			
		}
		wp_reset_postdata();
   }
}
// End Function Related POST

function zz_after_content($content) {
	ob_start();
	zz_related_post();
	$after_content = ob_get_clean();
	$custom_content = $content . $after_content;
	return $custom_content;
}
add_filter( 'the_content', 'zz_after_content');


?>

Just see your single post . And Related post will be on the bottom after content.

How To Include Javascript and CSS on Shortcode WordPress Plugin

Some weeks ago i try to find to include javascript and css on a shortcode only when the file is needed. After some search on the internet here is which i think the most efficient way.

First we must register file resource which we need, so we can call in the shortcode using wp_register_script and wp_register_style

// First register resources with init 
function zz_shortcode_resource() {
	wp_register_script("zz-shortcode-jscss-script", plugins_url("script.js", __FILE__), array('jquery'), "1.0", false);
	wp_register_style("zz-shortcode-jscss-style", plugins_url("style.css", __FILE__), array(), "1.0", "all");
}
add_action( 'init', 'zz_shortcode_resource' );

After that we call our shortcode function with wp_enqueue_script and wp_enqueue_style

add_shortcode( 'zz_shortcode_jscss', 'zz_shortcode_jscss' );
function zz_shortcode_jscss( $attr , $content) {
	$a = shortcode_atts( array(
	  'text' => ''
	), $attr );
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script("zz-shortcode-jscss-script",array('jquery') , '1.0', true);
	wp_enqueue_style("zz-shortcode-jscss-style");
	return '<div class="zz-sc-jscss">' . $a['text'] .'</div>';
}

Here is the complete source code in plugin so you can use it :

<?php
/*
Plugin Name: ZZ Shortcode With JS and CSS
Plugin URI: http://www.wpamanuke.com
Description: Include Javascript File and CSS Files on the Shortcode . Example [zz_shortcode_jscss text="HELLO CODE"][/zz_shortcode_jscss]
Version: 1.0.1
Author: WPAmaNuke
Author URI: https://wpamanuke.com
*/

// First register resources with init 
function zz_shortcode_resource() {
	wp_register_script("zz-shortcode-jscss-script", plugins_url("script.js", __FILE__), array('jquery'), "1.0", false);
	wp_register_style("zz-shortcode-jscss-style", plugins_url("style.css", __FILE__), array(), "1.0", "all");
}
add_action( 'init', 'zz_shortcode_resource' );

add_shortcode( 'zz_shortcode_jscss', 'zz_shortcode_jscss' );
function zz_shortcode_jscss( $attr , $content) {
	$a = shortcode_atts( array(
	  'text' => ''
	), $attr );
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script("zz-shortcode-jscss-script",array('jquery') , '1.0', true);
	wp_enqueue_style("zz-shortcode-jscss-style");
	return '<div class="zz-sc-jscss">' . $a['text'] .'</div>';
}

Here is the style.css . Because it’s only sample , so we need only little css to show that it is working

.zz-sc-jscss {
	padding:30px;
	background-color:#ff0000;
	color:#ffffff;
}

For javascript script.js . Just showing alert for simple showing the code working

jQuery( document ).ready(function($) {
	alert('This is from shortcode with js and css');
});

Ok. That’s how to include javascript and css on shortcode. I just record it , so if sometime i will need it , i just see this blog records

How To Create Dashboard Widget WordPress Plugin

Dashboard widget is widget which is shown in the administration dashboard.

Code which ussualy used :

  • wp_add_dashboard_widget
  • add_action , wp_dashboard_setup

The minimalist code which can be used :

/**
 * Add a widget to the dashboard.
 *
 * This function is hooked into the 'wp_dashboard_setup' action below.
 */
function zz_add_dashboard_widgets() {

	wp_add_dashboard_widget(
                 'zz_dashboard_widget',         // Widget slug.
                 'ZZ Dashboard Widget',         // Title.
                 'zz_dashboard_widget_function' // Display function.
        );	
}
add_action( 'wp_dashboard_setup', 'zz_add_dashboard_widgets' );

/**
 * Create the function to output the contents of our Dashboard Widget.
 */
function zz_dashboard_widget_function() {

	// Display whatever it is you want to show.
	echo "<h2>RSS Feed</h2>";
	output_rss_feed('http://wpamanuke.com/?feed=rss', 5, true, true, 200);
}

Complete Code

<?php
/*
Plugin Name: ZZ Dashboard Widgets
Plugin URI: http://www.wpamanuke.com
Description: Sample Dashboard Widgets Code
Version: 1.0.1
Author: WPAmaNuke
Author URI: https://wpamanuke.com
*/

/**
 * Add a widget to the dashboard.
 *
 * This function is hooked into the 'wp_dashboard_setup' action below.
 */
function zz_add_dashboard_widgets() {

	wp_add_dashboard_widget(
                 'zz_dashboard_widget',         // Widget slug.
                 'ZZ Dashboard Widget',         // Title.
                 'zz_dashboard_widget_function' // Display function.
        );	
}
add_action( 'wp_dashboard_setup', 'zz_add_dashboard_widgets' );

/**
 * Create the function to output the contents of our Dashboard Widget.
 */
function zz_dashboard_widget_function() {

	// Display whatever it is you want to show.
	echo "<h2>RSS Feed</h2>";
	output_rss_feed('http://wpamanuke.com/?feed=rss', 5, true, true, 200);
}

function get_rss_feed_as_html($feed_url, $max_item_cnt = 10, $show_date = true, $show_description = true, $max_words = 0)
{
    $result = "";
    // get feeds and parse items
    $rss = new DOMDocument();
	$rss->load($feed_url);

    $feed = array();
    foreach ($rss->getElementsByTagName('item') as $node) {
        $item = array (
            'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
            'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
            'content' => $node->getElementsByTagName('description')->item(0)->nodeValue,
            'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
            'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
        );
        $content = $node->getElementsByTagName('encoded'); // <content:encoded>
        if ($content->length > 0) {
            $item['content'] = $content->item(0)->nodeValue;
        }
        array_push($feed, $item);
    }
    // real good count
    if ($max_item_cnt > count($feed)) {
        $max_item_cnt = count($feed);
    }
    $result .= '<ul class="feed-lists">';
    for ($x=0;$x<$max_item_cnt;$x++) {
        $title = str_replace(' & ', ' & ', $feed[$x]['title']);
        $link = $feed[$x]['link'];
        $result .= '<li class="feed-item">';
        $result .= '<div class="feed-title"><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong></div>';
        if ($show_date) {
            $date = date('l F d, Y', strtotime($feed[$x]['date']));
            $result .= '<small class="feed-date"><em>Posted on '.$date.'</em></small>';
        }
        if ($show_description) {
            $description = $feed[$x]['desc'];
            $content = $feed[$x]['content'];
            // find the img
            $has_image = preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $content, $image);
            // no html tags
            $description = strip_tags(preg_replace('/(<(script|style)\b[^>]*>).*?(<\/\2>)/s', "$1$3", $description), '');
            // whether cut by number of words
            if ($max_words > 0) {
                $arr = explode(' ', $description);
                if ($max_words < count($arr)) {
                    $description = '';
                    $w_cnt = 0;
                    foreach($arr as $w) {
                        $description .= $w . ' ';
                        $w_cnt = $w_cnt + 1;
                        if ($w_cnt == $max_words) {
                            break;
                        }
                    }
                    $description .= " ...";
                }
            }
            // add img if it exists
            if ($has_image == 1) {
                $description = '<img class="feed-item-image" src="' . $image['src'] . '" />' . $description;
            }
            $result .= '<div class="feed-description">' . $description;
            $result .= ' <a href="'.$link.'" title="'.$title.'">Continue Reading »</a>'.'</div>';
        }
        $result .= '</li>';
    }
    $result .= '</ul>';
    return $result;
}
function output_rss_feed($feed_url, $max_item_cnt = 10, $show_date = true, $show_description = true, $max_words = 0)
{
    echo get_rss_feed_as_html($feed_url, $max_item_cnt, $show_date, $show_description, $max_words);
}

How To Create Custom Post Type WordPress Plugin

In WordPress, post and page represent contents for website. Taxonomy are categories for posts. You can create your won custom post type with plugin.

Some codes which we will use :

  • register_post_type
  • register_taxonomy
  • add_filter, single_template, taxonomy_template

Code to create custom post type

function wporg_custom_post_type()
{
    register_post_type('wporg_product',
                       array(
                           'labels'      => array(
                               'name'          => __('Products'),
                               'singular_name' => __('Product'),
                           ),
                           'public'      => true,
                           'has_archive' => true,
                           'rewrite'     => array( 'slug' => 'products' ), // my custom slug
                       )
    );
}
add_action('init', 'wporg_custom_post_type');

Code to create taxonomy

function wporg_register_taxonomy_course()
{
    $labels = [
        'name'              => _x('Courses', 'taxonomy general name'),
		'singular_name'     => _x('Course', 'taxonomy singular name'),
		'search_items'      => __('Search Courses'),
		'all_items'         => __('All Courses'),
		'parent_item'       => __('Parent Course'),
		'parent_item_colon' => __('Parent Course:'),
		'edit_item'         => __('Edit Course'),
		'update_item'       => __('Update Course'),
		'add_new_item'      => __('Add New Course'),
		'new_item_name'     => __('New Course Name'),
		'menu_name'         => __('Course'),
		];
	$args = [
		'hierarchical'      => true, // make it hierarchical (like categories)
		'labels'            => $labels,
		'show_ui'           => true,
		'show_admin_column' => true,
		'query_var'         => true,
		'rewrite'           => ['slug' => 'course'],
	];
	register_taxonomy('course', ['wporg_product'], $args);
}
add_action('init', 'wporg_register_taxonomy_course');

if you want to use template in plugin folder :

add_filter('single_template','your_single_template_function');
add_filter( 'taxonomy_template','your_taxonomy_template_function');

Here is the full code and don’t forget to change permalink after you activate the plugin, otherwise it will show 404 page :

<?php
/*
Plugin Name: ZZ Custom Post
Plugin URI: http://www.wpamanuke.com
Description: Sample Custom Post
Version: 1.0.1
Author: WPAmaNuke
Author URI: https://wpamanuke.com
*/

define( 'ZZ_PRODUCT_DIR' , plugin_dir_path( __FILE__ ) );
function wporg_custom_post_type()
{
    register_post_type('wporg_product',
                       array(
                           'labels'      => array(
                               'name'          => __('Products'),
                               'singular_name' => __('Product'),
                           ),
                           'public'      => true,
                           'has_archive' => true,
                           'rewrite'     => array( 'slug' => 'products' ), // my custom slug
                       )
    );
}
add_action('init', 'wporg_custom_post_type');


/* Filter the single_template with our custom function*/
add_filter('single_template', 'my_custom_template');


function my_custom_template($single) {

    global $post;

    /* Checks for single template by post type */
    if ( $post->post_type == 'wporg_product' ) {
        if ( file_exists( ZZ_PRODUCT_DIR . '/single.php' ) ) {
            return ZZ_PRODUCT_DIR . '/single.php';
        }
    }

    return $single;

}


function wporg_register_taxonomy_course()
{
    $labels = [
        'name'              => _x('Courses', 'taxonomy general name'),
		'singular_name'     => _x('Course', 'taxonomy singular name'),
		'search_items'      => __('Search Courses'),
		'all_items'         => __('All Courses'),
		'parent_item'       => __('Parent Course'),
		'parent_item_colon' => __('Parent Course:'),
		'edit_item'         => __('Edit Course'),
		'update_item'       => __('Update Course'),
		'add_new_item'      => __('Add New Course'),
		'new_item_name'     => __('New Course Name'),
		'menu_name'         => __('Course'),
		];
	$args = [
		'hierarchical'      => true, // make it hierarchical (like categories)
		'labels'            => $labels,
		'show_ui'           => true,
		'show_admin_column' => true,
		'query_var'         => true,
		'rewrite'           => ['slug' => 'course'],
	];
	register_taxonomy('course', ['wporg_product'], $args);
}
add_action('init', 'wporg_register_taxonomy_course');

function my_custom_archive( $template ) {
	 $mytemplate = ZZ_PRODUCT_DIR . '/archive.php';

    if( is_tax( 'course') && is_readable( $mytemplate ) )
        $template =  $mytemplate;

    return $template;
}
add_filter( 'taxonomy_template', 'my_custom_archive');

single.php

<?php
$args = [
    'post_type'      => 'wporg_product',
    'posts_per_page' => 10,
];
$loop = new WP_Query($args);
while ($loop->have_posts()) {
    $loop->the_post();
    ?>
    <div class="entry-content">
        <?php the_title(); ?>
        <?php the_content(); ?>
    </div>
    <?php
}

archive.php

<?php
$args = [
    'post_type'      => 'wporg_product',
    'posts_per_page' => 10,
];
$loop = new WP_Query($args);
while ($loop->have_posts()) {
    $loop->the_post();
    ?>
    <div class="entry-content">
        <a href="<?php the_permalink(); ?>" title=""><?php the_title(); ?></a>
        <?php the_content(); ?>
    </div>
    <?php
}

How To Create WordPress Plugin With Ajax

Ajax is the acronym for Asynchronous JavaScript And XML. It’s very usefull if you want to reload specify information from web server. It purpose to reload part of data on the web , so we don’t need to reload all website

To use ajax in WordPress , you need to know PHP and jQuery. Here is some wordpress api which you need to know to use ajax in wordpress :

  • add_action with wp_enqueue_scripts , wp_ajax_your_variable, wp_ajax_nopriv_your_variable
  • wp_create_nonce
  • wp_localize_script : to create variable which needed in javascript
  • check_ajax_referrer : check if referrer from same server
  • wp_die

Here is zz-ajax.php code :

<?php
/*
Plugin Name: ZZ Ajax
Plugin URI: http://www.wpamanuke.com
Description: Sample Ajax
Version: 1.0.1
Author: WPAmaNuke
Author URI: https://wpamanuke.com
*/

add_action( 'wp_enqueue_scripts', 'zz_ajax_enqueue_scripts' );
function zz_ajax_enqueue_scripts() {
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script( 'zz-ajax-script', plugins_url( '/test-ajax.js', __FILE__ ), array('jquery') , '1.0', true);
		
	$nonce = wp_create_nonce( 'zz_ajax_nonce' );
	wp_localize_script( 'zz-ajax-script', 'zz_ajax_var', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) , 'nonce' => $nonce ) );
	
}

add_action( 'wp_ajax_zz_ajax_action', 'zz_ajax_action' );
add_action( 'wp_ajax_nopriv_zz_ajax_action', 'zz_ajax_action' );
function zz_ajax_action() {
	check_ajax_referer( 'zz_ajax_nonce' , '_ajax_nonce' );
	echo "This is ajax message 1234";
	wp_die(); // this is required to terminate immediately and return a proper response
}

test-ajax.js code

jQuery(document).ready(function($) {
	
	var data = {
		'_ajax_nonce': zz_ajax_var.nonce,
		'action': 'zz_ajax_action'
	};
	
	jQuery.post(zz_ajax_var.ajax_url, data, function(response) {
		alert('Got this from the server: ' + response);
	});
	
});

How To Create ShortCode WordPress Plugin

Shortcode are special code in wordpress to show specific function with easy efforts. Shortcode is begin with [ and end with ]. For example function which we will display amazon product with shortcode [azproduct]. With shortcode you can use function coloring easily, or if you need only specific parameter change, shortcode is perfect for your needs.

To enable shortcode you must register it with function :

add_shortcode( 'your_shortcode_name', 'your_shortcode_function' );
function your_shortcode_function($attr,$content) {
}

Here is sample amazon link shortcode code :

<?php
/*
Plugin Name: ZZ Amazon Product ShortCode
Plugin URI: http://www.wpamanuke.com
Description: Sample ShortCode Code
Version: 1.0.1
Author: WPAmaNuke
Author URI: https://wpamanuke.com
*/

add_shortcode( 'azproduct', 'azproduct_link' );

// The callback function that will replace [azproduct]
function azproduct_link( $attr ) {
	
	$asin = '0385495323';
	if ( isset( $attr['asin'] ) ) {
		$asin = $attr['asin'];
	}
	
	$title= 'Buy Now';
	if ( isset( $attr['title'] ) ) {
		$title = $attr['title'];
	}
	
	return '<a href="http://www.amazon.com/dp/'. $asin .'" > '. $title .' </a > ';
}

add_shortcode( 'azproduct_content', 'azproduct_content' );
function azproduct_content( $attr , $content) {
	$a = shortcode_atts( array(
	  'color' => '',
	  'bgcolor' => ''
	), $attr );
	
	return '<div style="color:'. $a['color'] .';background-color:' . $a['bgcolor'] .';">'. $content . '</div>';
}
You can use shortcode in your editor with code like this : 
[azproduct asin="1476755744" title="Red Notice"]
[azproduct_content color="#ff0000" bgcolor="#cc0cc0"]This is contents[/azproduct_content]

How To Create WordPress Widget Plugin

Widget is small block which perform specific function. Widget ussualy put in the sidebar or footer. You can list widgets which are ready in your wordpress from admin area Appearance ยป Widgets section in your WordPress dashboard.

To program widget here is some codes skeletons which you need to know

function your_register_widgets() {
	register_widget('your_widget_class');
}
add_action('widgets_init', 'your_register_widgets');

class your_widget_class extends WP_Widget {
	function __construct() {
	}
	function widget($args, $instance) {
	}
	function update($new_instance, $old_instance) {
	}
	function form($instance) {
	}
}
<?php
/*
Plugin Name: ZZ Widgets
Plugin URI: http://www.wpamanuke.com
Description: Sample Widgets Code
Version: 1.0.1
Author: WPAmaNuke
Author URI: https://wpamanuke.com
*/

function zz_register_widgets() {
	register_widget('zz_widget');
}
add_action('widgets_init', 'zz_register_widgets');

class zz_widget extends WP_Widget { 
	function __construct() {
		parent::__construct(
			'zz_widget', esc_html_x( 'ZZ Widget' , 'widget name', 'zz-widget' ),
			array(
				'classname' => 'zz-widget',
				'description' => esc_html__( 'ZZ Widget Post ' , 'zz-widget' ),
				'customize_selective_refresh' => true
			)
		);
	}
	function widget($args, $instance) {
		$defaults = array('title' => '', 'category' => 0, 'tags' => '', 'postcount' => 5, 'offset' => 0, 'sticky' => 1);
        $instance = wp_parse_args($instance, $defaults);
		$query_args = array();
		$query_args['ignore_sticky_posts'] = $instance['sticky'];
		if (0 !== $instance['category']) {
			$query_args['cat'] = $instance['category'];
		}
		if (!empty($instance['tags'])) {
			$tag_slugs = explode(',', $instance['tags']);
			$tag_slugs = array_map('trim', $tag_slugs);
			$query_args['tag_slug__in'] = $tag_slugs;
		}
		if (!empty($instance['postcount'])) {
			$query_args['posts_per_page'] = $instance['postcount'];
		}
		if (0 !== $instance['offset']) {
			$query_args['offset'] = $instance['offset'];
		}
	    
		$widget_posts = new WP_Query($query_args);
		echo wp_kses_post( $args['before_widget'] );
			if ($widget_posts->have_posts()) :
				$last = $widget_posts->post_count;
				$i = 0;
				if (!empty($instance['title'])) {
					$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
					$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
					echo wp_kses_post( $args['before_title'] ) . esc_html( $title ) . wp_kses_post( $args['after_title'] );
				}
				echo '<ul class="zz-widget-block">' . "\n";
					while ($widget_posts->have_posts()) : $widget_posts->the_post();
						 echo "<li>
						<a href='";
						the_permalink();
						echo "'>";
						the_title();  
						echo "</a>
						</li>";
					endwhile;
				echo '</ul>' . "\n";
			endif;
			wp_reset_postdata();
			
		echo wp_kses_post( $args['after_widget'] );
		
    }
	function update($new_instance, $old_instance) {
        $instance = array();
        if (!empty($new_instance['title'])) {
			$instance['title'] = sanitize_text_field($new_instance['title']);
		}
        if (0 !== absint($new_instance['category'])) {
			$instance['category'] = absint($new_instance['category']);
		}
		if (!empty($new_instance['tags'])) {
			$tag_slugs = explode(',', $new_instance['tags']);
			$tag_slugs = array_map('sanitize_title', $tag_slugs);
			$instance['tags'] = implode(', ', $tag_slugs);
		}
		if (0 !== absint($new_instance['postcount'])) {
			if (absint($new_instance['postcount']) > 50) {
				$instance['postcount'] = 50;
			} else {
				$instance['postcount'] = absint($new_instance['postcount']);
			}
		}
		if (0 !== absint($new_instance['offset'])) {
			if (absint($new_instance['offset']) > 50) {
				$instance['offset'] = 50;
			} else {
				$instance['offset'] = absint($new_instance['offset']);
			}
		}
        return $instance;
    }
    function form($instance) {
        $defaults = array('title' => '', 'category' => 0, 'tags' => '', 'postcount' => 5, 'offset' => 0, 'sticky' => 1);
        $instance = wp_parse_args($instance, $defaults); ?>
        <p>
        	<label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e('Title:', 'zz-widget'); ?></label>
			<input class="widefat" type="text" value="<?php echo esc_attr($instance['title']); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" id="<?php echo esc_attr($this->get_field_id('title')); ?>" />
        </p>
		<p>
            <label for="<?php echo esc_attr($this->get_field_id('category')); ?>"><?php esc_html_e('Select a Category:', 'zz-widget'); ?></label>
            <select id="<?php echo esc_attr($this->get_field_id('category')); ?>" class="widefat" name="<?php echo esc_attr($this->get_field_name('category')); ?>">
            	<option value="0" <?php selected(0, $instance['category']); ?>><?php esc_html_e('All', 'zz-widget'); ?></option><?php
            		$categories = get_categories();
            		foreach ($categories as $cat) { ?>
            			<option value="<?php echo absint($cat->cat_ID); ?>" <?php selected($cat->cat_ID, $instance['category']); ?>><?php echo esc_html($cat->cat_name) . ' (' . absint($cat->category_count) . ')'; ?></option><?php
            		} ?>
            </select>
            <small><?php esc_html_e('Select a category to display posts from.', 'zz-widget'); ?></small>
		</p>
		<p>
        	<label for="<?php echo esc_attr($this->get_field_id('tags')); ?>"><?php esc_html_e('Filter Posts by Tags (e.g. lifestyle):', 'zz-widget'); ?></label>
			<input class="widefat" type="text" value="<?php echo esc_attr($instance['tags']); ?>" name="<?php echo esc_attr($this->get_field_name('tags')); ?>" id="<?php echo esc_attr($this->get_field_id('tags')); ?>" />
	    </p>
        <p>
        	<label for="<?php echo esc_attr($this->get_field_id('postcount')); ?>"><?php esc_html_e('Post Count (max. 50):', 'zz-widget'); ?></label>
			<input class="widefat" type="text" value="<?php echo absint($instance['postcount']); ?>" name="<?php echo esc_attr($this->get_field_name('postcount')); ?>" id="<?php echo esc_attr($this->get_field_id('postcount')); ?>" />
	    </p>
	    <p>
        	<label for="<?php echo esc_attr($this->get_field_id('offset')); ?>"><?php esc_html_e('Skip Posts (max. 50):', 'zz-widget'); ?></label>
			<input class="widefat" type="text" value="<?php echo absint($instance['offset']); ?>" name="<?php echo esc_attr($this->get_field_name('offset')); ?>" id="<?php echo esc_attr($this->get_field_id('offset')); ?>" />
	    </p><?php
    }
}

How To Create Twenty Nineteen Child Theme

Sometimes we need to create wordpress theme child for modification css only. We need to create child theme because regular update on parent theme so we don’t need to change code if there is new update. Here is the way to create child theme for Nineteen Child Theme :

  • Create folder nineteen-child
  • Create file style.css
  • Create file functions.php

That’s very simple. For the structure of sytle.css is like this :

/*
Theme Name: Twenty Nineteen Child
Theme URL: http://wpamanuke.com/
Description: Twenty Seventeen Child Theme
Author: WPAmaNuke
Author URL: http://wpamanuke.com/
Template: twentynineteen
Version: 1.0.0
Text Domain: twentynineteen-child
*/ 
/* Custom CSS goes after this line */

.entry .entry-title a {
	color:#ff0000;
}

For modifying css , you need to use firefox web developer inspector or chrome devtools and do some experiment

To include parent style.css you need to create file functions.php and add code like this :

<?php

	add_action( 'wp_enqueue_scripts', 'tnt_enqueue_parent_styles' );

	function tnt_enqueue_parent_styles() {
	   wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
	}

?>

How To Create WordPress Plugin

To Create WordPress Plugin you need to know how basic php , css and html works.
Here is some function which ussually i used for wordpress plugin.

PREFIX

It’s suggested to prefix your function and variable. For example using mfp (My First Plugin). Here is the example $mfp_string , mfp_function.

DIR and URL

You can detect directory and url WordPress Plugin using function plugin_dir_path( FILE ) and plugin_dir_url( FILE ).
I ussually use constant some constanta like this :

define( 'MFP_DIR' , plugin_dir_path( __FILE__ ) );
define( 'MFP_URL' , plugin_dir_url( __FILE__ ) );

HOOK

Hook is function so you don’t need to change the core code. There are 2 hooks : action and filter.

ACTION

Here are some function which you need to know : do_action , add_action and remove_action

DO_ACTION

For example your index.php in theme like this

<?php
	do_action( 'mfp_header_before' );
	echo '<div>HEADER</div>';
	do_action( 'mfp_header_after' );
	
	do_action( 'mfp_content_before' );
	echo '<div>CONTENT</div>';
	do_action( 'mfp_content_after' );
	
	do_action( 'mfp_footer_before' );
	echo '<div>FOOTER</div>';
	do_action( 'mfp_footer_after' );

?>

ADD_ACTION

You can add action in the plugin without change index.php in the theme. For example :

<?php
	function mfp_example_header_before1() {
		echo '<div>HEADER BEFORE 1</div>';
	}
	add_action( 'mfp_header_before','mfp_example_header_before1' );
	
	function mfp_example_header_before2() {
		echo '<div>HEADER BEFORE 2</div>';
	}
	add_action( 'mfp_header_before','mfp_example_header_before2' );
	
	function mfp_example_footer_before1() {
		echo '<div>FOOTER BEFORE 1</div>';
	}
	add_action( 'mfp_footer_before','mfp_example_footer_before1' );
?>

REMOVE_ACTION

If you want to remove just use for example remove_action( ‘mfp_header_before’,’mfp_example_header_before2′ ); or if you want to remove all action remove_all_actions( ‘mfp_header_before’ );

WORDPRESS ACTION STANDAR WHICH YOU NEED TO KNOW : wp_head , wp_footer

FILTER

Filter is hook for variable. Function which you need to know apply_filters and add_filter.
Example :

<?php
	function mfp_do_filter( $mfp_text ) {
		$mfp_text = "VAR DO FILTER";
		return $mfp_text;
	}
	add_filter( 'mfp_var_filter', 'mfp_do_filter' );
	
	function mfp_apply_filter() {
		$mfp_var = "VAR APPLY FILTER";
		$mfp_var = apply_filters( 'mfp_var_filter' , $mfp_var );
		echo $mfp_var;
	}
	
	mfp_apply_filter();
?>

REMOVE_FILTER

If you want to remove filter. Just use for example remove_filter( ‘mfp_var_filter’ , ‘mfp_do_filter’ ); or if you want ro remove all just use function remove_all_filter( ‘mfp_var_filter’ );

WORDPRESS FILTER WHICH YOU NEED TO KNOW : the_content

After you know some basic functions now it’s time to create your first plugin.
HERE IS SAMPLE FIRST PLUGIN TO INSERT BEFORE AND AFTER CONTENT IN THE POST / PAGE

<?php
/*
Plugin Name: My First Plugin
Plugin URI: http://wpamanuke.com/how-to-create-wordpress-plugin/
Description: First plugin which i made
Version: 1.0
Author: WPAmanuke
Author URI: http://wpamanuke.com
License: GPLv2
*/

function mfp_filter_the_content_before( $content ) {
    $custom_content = '<div>Before Content Filter</div>';
    $custom_content .= $content;
    return $custom_content;
}
add_filter( 'the_content', 'mfp_filter_the_content_before' );

function mfp_filter_the_content_after( $content ) {
    $custom_content = '<div>After Content Filter</div>';
    $custom_content = $content . $custom_content;
    return $custom_content;
}
add_filter( 'the_content', 'mfp_filter_the_content_after' );

?>

Simple HTML Tutorial

HTML is the standard markup language for creating Web pages. Before you code wordpress theme, first you must learn html and css. HTML is the standard markup language for creating Web pages. Because HTML describe structure of web pages using markup and the markup is element to build html block.
The most basic html document is like this :

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    </body>
    </html>

NOTES

  • The <head> element contains meta information about the document
  • The <body> element contains the visible page content

Here is simple standard HTML Document

    <!DOCTYPE html>
    <html>
    <head>
        <title>My Title</title>
    </head>
    <body>
        <h1>My Heading</h1>
        <p>My Paragraph.</p>
    </body>
    </html>

The output above html will be like this :

Because the output still plain , you need to styling the html with css. Styling here means coloring , font-size , padding etc.
Here the sample styling with embedded css ( using style ) :

    <!DOCTYPE html>
    <html>
    <head>
        <title>My Title</title>
        <style>
            h1 {
                color: #ff0000;
                font-size: 50px;
                text-transform: uppercase;
            }
            p {
                color: #0000ff;
                font-size: 30px;
            }
        </style>
    </head>
    <body>
        <h1>My Heading</h1>
        <p>My Paragraph.</p>
    </body>
    </html>

And here is the output

I hope this simple html tutorial help you to know very basic HTML and CSS