Category Archives: Wordpress

Create Plugin From Custom Post Type

1. Create folder with name “rar-portfolio” in plugins folder.
2. Create a file name with “portfolio.php”.
3. Add below code into “portfolio.php”.

Note: Create custom post type on plugin activation with short code

We used this custom post type : Create and display custom post type with Texonomy, Metabox and Tag


<?php
/**
 * Plugin Name: RAR Portfolio
 * Plugin URI: http://rarthemes.com
 * Description: Create custom post type on plugin activation with short code
 * Version: 1.0.0
 * Author: Ravi Radadiya
 * Author URI: http://rarthemes.com
 * License: GPL2
 */
 
/***** Start custom post type - Portfolios *****/
function portfolios_custom_init() {
$labels = array(
'name' => __('Portfolios','themename'),
'singular_name' => __('portfolios','themename'),
'add_new' => __('Add New','themename'),
'add_new_item' => __('Add New Portfolio','themename'),
'edit_item' => __('Edit Portfolio','themename'),
'new_item' => __('New Portfolio','themename'),
'all_items' => __('All Portfolios','themename'),
'view_item' => __('View Portfolios','themename'),
'search_items' => __('Search Portfolio','themename'),
'not_found' => __('No Portfolios found','themename'),
'not_found_in_trash' => __('No Portfolios found in Trash','themename'),
'parent_item_colon' => '',
'menu_name' => __('Portfolios','themename')
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'portfolios' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor','thumbnail')
 
);
register_post_type( 'portfolios', $args );
register_taxonomy("portfolio-categories",
array("portfolios"),
array("hierarchical" => true,
'show_admin_column'   => true,
"label" => "Portfolio Categories",
"singular_label" => "Portfolio Categories",
"rewrite" => array( 'slug' => 'portfolio_category' ,
 
)));
 
register_taxonomy("portfolio-tag",
array("portfolios"),
array("hierarchical" => false,
'show_admin_column'   => true,
"label" => "Portfolio Tag",
"singular_label" => "Portfolio tag",
"rewrite" => array( 'slug' => 'portfolio_tag' ,
 
)));
 
}
add_action( 'init', 'portfolios_custom_init' );
 
/*****  Custom Meta Box - portfolios *****/
 
add_action( 'add_meta_boxes', 'meta_box_portfolio' );
function meta_box_portfolio()
{
add_meta_box( 'meta_box_portfolio_id', 'Enter Portfolio info', 'portfolio_website_info', 'portfolios', 'normal', 'high' );
}
function portfolio_website_info( $post )
{
$values = get_post_custom( $post->ID );
$portfolio_url = isset( $values['portfolio_url'] ) ? esc_attr( $values['portfolio_url'][0] ) : '';
$portfolio_text = isset( $values['portfolio_text'] ) ? esc_attr( $values['portfolio_text'][0] ) : '';
$portfolio_image = isset( $values['portfolio_image'] ) ? esc_attr( $values['portfolio_image'][0] ) : '';
 
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>

<p>Portfolio URL</p>
<input type="text" name="portfolio_url" value="<?php echo esc_url( $portfolio_url ); ?>" class="widefat" placeholder="Portfolio Url" />
<p>Portfolio Text</p>
<input type="text" name="portfolio_text" value="<?php echo esc_attr( $portfolio_text ); ?>" class="widefat" placeholder="Portfolio Text" />
<p>Portfolio Image</p>
<input id=""  type="text" class=" mytheme_media_url upload" name="portfolio_image" value="<?php echo esc_attr( $portfolio_image ); ?>" placeholder="No file chosen"  />
<?php if(!empty($instance['image'])) { ?>
<img src="<?php echo $instance['image']; ?>"  />
<?php } ?>
<input id="mytheme_image_uploader"  class="button mytheme_media_upload" type="button" value="Upload" />
<?php
} 
add_action( 'save_post', 'portfolio_meta_box_save' );
function portfolio_meta_box_save( $post_id )
{
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
if( isset( $_POST['portfolio_url'] ) ) update_post_meta( $post_id, 'portfolio_url', esc_url( $_POST['portfolio_url'] ) );
if( isset( $_POST['portfolio_text'] ) ) update_post_meta( $post_id, 'portfolio_text', esc_attr( $_POST['portfolio_text'] ) );
if( isset( $_POST['portfolio_image'] ) ) update_post_meta( $post_id, 'portfolio_image', esc_attr( $_POST['portfolio_image'] ) );
}
/*** end portfolio post type ***/

/* Register activation hook */
function portfolio_plugin_activation() {
    portfolios_custom_init();
   // flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'portfolio_plugin_activation' );

/* Display posts */

function display_portfolio(){
	?>
<div class="row">
  <?php
$legal_portfolio_args = array(
'paged' => $paged,
'orderby' => 'post_date',
'order' => 'ASC',
'post_type' => 'portfolios',
'post_status' => 'publish'
);
$legal_portfolio = new WP_Query( $legal_portfolio_args );
while ( $legal_portfolio->have_posts() ) { $legal_portfolio->the_post();
?>
  <div class="col-md-6 col-sm-6 attorneys">
    <div class="our-section-box">
      <?php if ( has_post_thumbnail() ) { ?>
      <a href="<?php the_permalink(); ?>" target="_blank">
      <div class="col-md-12 no-padding our-box-left">
        <?php the_post_thumbnail( 'legal-ourteam-thumbnail-image', array( 'alt' => get_the_title(), 'class' => 'img-responsive') ); ?>
      </div>
      </a>
      <?php } ?>
      <div class="col-md-12 our-box-right">
        <h4>
          <?php the_title(); ?>
        </h4>
        <?php the_content(); ?>
        <?php
echo 'URL: '.  get_post_meta( get_the_ID(), 'portfolio_url', true );
echo '<br>text: '. get_post_meta( get_the_ID(), 'portfolio_text', true );
echo '<br>Image: '. get_post_meta( get_the_ID(), 'portfolio_image', true );
echo '<br>Category: '; foreach((get_the_terms($post->ID, 'portfolio-categories')) as $term) { echo $term->name. ' ,'  ; }
echo '<br>tag: '; foreach((get_the_terms($post->ID, 'portfolio-tag')) as $term) { echo $term->name. ' ,'  ; }
?>
      </div>
    </div>
  </div>
  <?php } ?>
</div>
<?php
}

/* Add short code */

add_shortcode('rar_portfolio', 'portfolio_shortcode');
function portfolio_shortcode(){ 
	return display_portfolio();
}

Advertisements

Disable wordpress admin for non administer users

/* Disable wordpress admin for non administer users*/

add_action( 'init', 'blockusers_init' );
function blockusers_init() {
    if ( is_admin() && ! current_user_can( 'administrator' ) &&
       ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
        wp_redirect( home_url() );
        exit;
    }
}

Add Download Button and Counter Using WordPress Ajax

Add below code into functions.php

/* Enque script for ajax */
add_action('wp_enqueue_scripts', 'download_counter_enqueue');
function download_counter_enqueue() {
	wp_register_script('ajax-download-script', get_template_directory_uri() . '/js/dowload-counter.js', array('jquery'));
	wp_enqueue_script('ajax-download-script');
	wp_localize_script('ajax-download-script', 'ajax_download_object', array('ajaxurl' => admin_url('admin-ajax.php')));
}  

/* Insert download counter using ajax */
function download_counter() {
    //update_post_meta(45, 'themes_downloads', 45);
    $wp_id = $_POST['wp_id'];
    $wp_downloaded = $_POST['wp_downloaded'];
   
    $wp_downloads_count = $wp_downloaded + 1;
    $wp_downloads = update_post_meta($wp_id, 'wp_downloads', $wp_downloads_count );
}
add_action( 'wp_ajax_download', 'download_counter' );
add_action( 'wp_ajax_nopriv_download', 'download_counter' );

Create new javascript file (dowload-counter.js)

/* WP themes Download counter */	
jQuery(document).ready(function($) {
	 $("a").click(function(){
     $("#ajaxform").submit();
     $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_download_object.ajaxurl,
            data: {
                    'action': 'download', //calls wp_ajax_nopriv_ajaxdownload
                    'wp_id': $('form#ajaxform #wp_id').val(),
                    'wp_downloaded': $('form#ajaxform #wp_downloaded').val(),
                  },
            success: function(){ }
        });
  });
});

Add below form and button code in sigle file (single.php)

$wp_downloaded = get_post_meta($post->ID, 'wp_downloads', true); ?>
<form id="ajaxform" action="ajaxform" method="post">
    <input type="hidden" name="wp_id" id="wp_id" value="<?php echo $post->ID; ?>" />
    <input type="hidden" name="wp_downloaded" id="wp_downloaded" value="<?php echo $wp_downloaded; ?>" />
    <input type="submit" name="submit" style="display:none;"/>
</form>
<a href="#">Download</a> <?php echo $wp_downloaded;

WordPress Practical Interview questions – fronted

<?php

//=====================================================================
//	Display posts list
//=====================================================================

$args = array( 
			'post_type' => 'post', 
		);
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();	
endwhile;

//=====================================================================
//	Display posts meta
//=====================================================================

echo get_post_meta(get_the_ID(),'meta_key',true); 

//=====================================================================
//	Display sidebar
//=====================================================================

if ( is_active_sidebar( 'sidebar-1' )  ) :
	dynamic_sidebar('sidebar-1');
endif;	

//=====================================================================
//	WordPress Loop
//=====================================================================

if ( have_posts() ) : // check post is avalable or not,if yes then will go for next step
while ( have_posts() ) : // if you had configured your WordPress reading settings to display five posts on the home page then while loop five times and then stop.
the_post(); // This sets up the post and allows us to retrieve any part of the post including the content, the publication date, the author, the category etc.

// the_post function code
function the_post() {
    global $wp_query;
    $wp_query->the_post();
}

if ( have_posts() ) : while ( have_posts() ) : the_post();
	// DO SOMETHING WITH EACH POST THAT WE FOUND
	endwhile; else: 
	// DO SOMETHING IF NOTHING WAS FOUND
endif;

//=====================================================================
//	WordPress WP Query
//=====================================================================

// The retrieved dataset is stored in the $wp_query object.
// List of Query Vars (https://codex.wordpress.org/WordPress_Query_Vars#Query_variables)
// If you use the_post() with your query, you need to run "wp_reset_postdata()" afterwards to have Template Tags use the main query’s current post again.

// Example 1
$query = new WP_Query('cat=14,15 & posts_per_page=3 & order=ASC');
while ( $query->have_posts() ) : $query->the_post();
	// Your code here
endwhile;
wp_reset_postdata(); // Restore original Post Data

// Example 2
// Full list of parameters (https://codex.wordpress.org/Class_Reference/WP_Query#Parameters)
// Methods and properties (https://codex.wordpress.org/Class_Reference/WP_Query#Methods_and_Properties)
$args = array( 'arg_1' => 'val_1', 'arg_2' => 'val_2' );
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
	while ( $query->have_posts() ) : $query->the_post(); 
		// Your code here
	endwhile;
	} else {
        // no posts found
	}
wp_reset_postdata();

//=====================================================================
//	WordPress WP Meta Query
//=====================================================================

// To build a query based on a single custom field, we just need one or more of the following arguments:
//(meta_key, meta_value, meta_type, meta_compare)

$args = array( 
		'post_type' => 'my_post_tname',
		
		// For single key and value
		'meta_key'     => 'my_meta_key',
		'meta_value'   => 'value1',	
		
		// For multiple key and value
		'meta_query' => array(
			array(
				'key'     => 'my_meta_key',
				'value'   => array ('value1','value2'),
			),
			array(
				'key'     => '_thumbnail_id',
				'compare'   => 'EXISTS',
		),)
);
$query = new WP_Query( $args );
while ( $loqueryop->have_posts() ) : $query->the_post();
	echo 'Name : '. get_post_meta(get_the_ID(),'my_meta_key',true); 
endwhile;
wp_reset_postdata();	

//=====================================================================
//	WordPress WP Tax Query
//=====================================================================

$args = array( 
		'post_type' => 'my_post_tname',
		'tax_query' => array(
			 array(
				'taxonomy' => 'projects',
				
				// With slug name
				'field' => 'slug',
				'terms' => array('apartment','farm-house'),
				
				// With ID
				'terms' => array('3','5'),
				
				'operator' => 'NOT IN',
				
		)),	
);

//=====================================================================
//	Custom Search form
//=====================================================================

// Copy and pest your default search form code in perticular page and add your custom post type name in below hidden input field. 
<input type="hidden" name="post_type" value="portfolio">

// Change search function globally to search only post, page and portfolio post types
function prefix_limit_post_types_in_search( $query ) {
    if ( $query->is_search ) {
        $query->set( 'post_type', array( 'post','page', 'portfolio' ) );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'prefix_limit_post_types_in_search' );




WordPress Practical Interview questions – backend

<?php

//=====================================================================
//	Register custom post type
//=====================================================================

add_action('init','custom_posttype_function_name');
function custom_posttype_function_name(){
	$labels = array(
		'name' => _x( 'Realestates', 'post type general name', 'your-plugin-textdomain' ),
	);
	$args = array(
		'labels' => $labels,
		'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
	);
	register_post_type( 'custom_posttype_name', $args );
}

//=====================================================================
//	Register taxonomy for custom post type
//=====================================================================

// Note : hierarchical 'true' for category
// Note : hierarchical 'false' for tag

$labels = array(
				'name' => _x( 'Location', 'taxonomy general name', 'textdomain' ),
		   );
$args = array(
			'hierarchical' => true,
			'labels'=> $labels,
		);
register_taxonomy( 'taxonomy_name', 'custom_posttype_name', $args );

//=====================================================================
//	Create meta box
//=====================================================================

add_action( 'add_meta_boxes', 'meta_box_realestate' );
function meta_box_realestate() {
	add_meta_box( 'meta_box_realestate_id', 'Enter Realestate Info', 'realestate_meta_boxes_info', 'realestate', 'normal', 'high' );
}

function realestate_meta_boxes_info( $post ) {
	$values = get_post_custom( $post->ID );
	$realestate_owner = isset( $values['realestate_owner'] ) ? esc_attr( $values['realestate_owner'][0] ) : '';
 	wp_nonce_field( 'realestate_meta_box_nonce_action', 'realestate_meta_box_nonce_field' ); ?>Portfolio Text

<input type="text" name="realestate_owner" value="<?php echo esc_attr( $realestate_owner ); ?>" class="widefat" placeholder="Portfolio Text" /><?php
}

add_action( 'save_post', 'realestate_meta_boxes_info_save' );
function realestate_meta_boxes_info_save( $post_id ) {
	if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
	if( !isset( $_POST['realestate_meta_box_nonce_field'] ) || !wp_verify_nonce( $_POST['realestate_meta_box_nonce_field'], 'realestate_meta_box_nonce_action' ) ) return;
	if( isset( $_POST['realestate_owner'] ) ) update_post_meta( $post_id, 'realestate_owner', esc_attr( $_POST['realestate_owner'] ) );
}  

//=====================================================================
//	Create nonce field for meta box
//=====================================================================

// wp_nonce_field use for security
// https://codex.wordpress.org/Function_Reference/wp_nonce_field

wp_nonce_field( 'realestate_meta_box_nonce_action', 'realestate_meta_box_nonce_field' );

//=====================================================================
//	Register sidebar
//=====================================================================
add_action( 'widgets_init', 'theme_slug_widgets_init' );
function theme_slug_widgets_init() {
    register_sidebar( array(
        'name' => __( 'Main Sidebar', 'theme-slug' ),
        'id' => 'sidebar-1',
        ) );
} 

//=====================================================================
//	Register sidebar
//=====================================================================
add_action('widgets_init', 'my_widget');
function my_widget() {
    register_widget('my_widget_class_name');
}

//=====================================================================
//	Wordpress Hook - Action
//=====================================================================

// Actions hook allow you to add extra functionality at a specific point in the processing of the page for example - add widgets, menus, send email on publis post.

add_action( $hook, $function_to_add, $priority, $accepted_args ); // Add Hooks
remove_action( $tag, $function_to_remove, $priority ); // Remove Hook

// 200+ hooks avalable in WordPress. Below few examples of common hooks in use.

// Register a Custom Menu in the Admin
function register_my_custom_menu_page() {
 add_menu_page( 'custom menu title', 'custom menu', 'manage_options', 'myplugin/myplugin-admin.php', '', 'dashicons-admin-site', 6 );
}
add_action( 'admin_menu', 'register_my_custom_menu_page' );

// Hook into Post Publishing
function publish_post_tweet($post_ID) {
  global $post;
  // Code to send a tweet with post info
}
add_action('publish_post', 'publish_post_tweet');

// Hook Into Widget Initialization
function create_my_widget() {
 register_sidebar(array(
 'name' => __( 'My Sidebar', 'mytheme' ),
 'id' => 'my_sidebar',
));
}
add_action( 'widgets_init', 'create_my_widget' );

// Hook Into Front-end Scripts and Styles
function theme_styles() {
 wp_enqueue_style( 'main_css', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles' );

//=====================================================================
//	Wordpress Hook - Filter
//=====================================================================

// Filter hook allows you modify WordPress data for example - excerpts length, 

add_filter( $tag, $function_to_add, $priority, $accepted_args ); // Add Filter
remove_filter( $tag, $function_to_remove, $priority ); // Remove Filter

//Change the Excerpt Length
function excerpt_length_example( $words ) {
 return 15;
}
add_filter( 'excerpt_length', 'excerpt_length_example' );

// Add extra content before default page content
add_filter( 'the_content', 'add_extra_content');
function add_extra_content( $content ) {
$custom_content = 'YOUR CONTENT GOES HERE'.$content;
return $custom_content;
}

//=====================================================================
//	Theme Options
//=====================================================================

// Register settings for save theme options page values (it will store in wp_options table)
add_action('admin_init', 'legal_options_init');
function legal_options_init() {
	//register_setting( $option_group, $option_name, $sanitize_callback );
    register_setting('legal_options', 'legal_theme_options', 'legal_options_validate');
}
function legal_options_validate($input) {
	// validate, sanitize code here.
}

// Add theme options menu and page
add_action('admin_menu', 'theme_options_menu');
function theme_options_menu() {
	// add_theme_page( $page_title, $menu_title, $capability, $menu_slug, $function );
	add_theme_page('Theme Options', 'Theme Options', 'edit_theme_options', 'themeoptions_framework', 'legal_framework_page');
}
function legal_framework_page() {
	settings_fields('legal_options');
    $legal_options = get_option('legal_theme_options');

	?><input id="email" name="legal_theme_options[email]" type="text" value="<?php if (!empty($legal_options['email'])) { echo esc_attr($legal_options['email']);} ?>" /><?php
}

// For display theme options value on frontend
$legal_options = get_option('legal_theme_options');
if (!empty($legal_options['email'])) { echo esc_attr($legal_options['email']); }

//=====================================================================
//	Create Shortcode
//=====================================================================
function my_shortcode() {
  return 'I am wordpress developer';
}
add_shortcode('developer', 'my_shortcode');

// For display Shortcode result on frontend
echo do_shortcode( '[developer]' );

//=====================================================================
//	Wordpress Ajax
//===================================================================== 

// Edit your custom template to include a form or javascript event that will submit data via jQuery AJAX to admin-ajax.php including whatever post data you want to pass in.
// Enque required files : jQuery, admin-ajax.php with wp_localize_script.
// Define a function in your theme’s function.php; read post variables, and return something back to the user if you wish.
// Add an AJAX action hook for your function.

// do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ); - (action is defined on javascript data)this hook is fired if the current viewer is not logged in
// do_action( 'wp_ajax_' . $_POST['action'] ); - if logged in:

add_action( 'wp_ajax_download', 'my_ajax' );
add_action( 'wp_ajax_nopriv_download', 'my_ajax' );
function my_ajax() {
	// Your code here
	wp_die();
}

//=====================================================================
//  Plugin Activation 
//=====================================================================

function myplugin_activation() {
    my_custom_post_type_portfolio(); // Activation code here (Custom post type's function name)
}
register_activation_hook( __FILE__, 'myplugin_activation' );

Event

Download Free Responsive WordPress Themes. We have Shortlisted Some the Best WordPress Themes for Your Website.

Source: Event

Disable Update Notifications for WordPress

1. To Disable Update WordPress nag :

add_action('after_setup_theme','remove_core_updates');
function remove_core_updates()
{
if(! current_user_can('update_core')){return;}
add_action('init', create_function('$a',"remove_action( 'init', 'wp_version_check' );"),2);
add_filter('pre_option_update_core','__return_null');
add_filter('pre_site_transient_update_core','__return_null');
}

2. To Disable Plugin Update Notifications :

remove_action('load-update-core.php','wp_update_plugins');
add_filter('pre_site_transient_update_plugins','__return_null');

3. To Disable all the Nags & Notifications :

function remove_core_updates(){
global $wp_version;return(object) array('last_checked'=> time(),'version_checked'=> $wp_version,);
}
add_filter('pre_site_transient_update_core','remove_core_updates');
add_filter('pre_site_transient_update_plugins','remove_core_updates');
add_filter('pre_site_transient_update_themes','remove_core_updates');
%d bloggers like this: