Tag: Wordpress

WordPress Change Default Post URL

If we need to add custom slug in URL then used below snippet to change it. Add code in functions.php

function filter_post_link($permalink, $post) {
	if ($post->post_type == 'post') {
        return '/blog/'.$permalink;
	}   
    return $permalink;
}
add_filter('pre_post_link', 'filter_post_link', 10, 2);
Advertisements

WordPress custom taxonomy custom hierarchical

Custom taxonomy hierarchical with ul li list and checkbox and radio button.


function get_product_taxonomie($taxonomies = 'product_category', $input_type = 'radio', $input_class = 'categoryCheck') {function get_product_taxonomie($taxonomies = 'product_category', $input_type = 'radio', $input_class = 'categoryCheck') { $selected_term = ''; $selected_term_open = ''; if($taxonomies == 'product_category'){ $selected_term = get_query_var('cats'); $selected_term_open = get_query_var('cats'); if(empty($selected_term)){ $selected_term = get_queried_object()->term_id; $selected_term_open = get_queried_object()->term_id; } } else if($taxonomies == 'product_brand'){ $selected_term = get_query_var('brands'); $selected_term_open = get_query_var('brands'); if(empty($selected_term)){ $selected_term = get_queried_object()->term_id; $selected_term_open = get_queried_object()->term_id; } } $selected_term = explode(',', $selected_term); $args = array( 'orderby'           => 'name',  'order'             => 'ASC', 'hide_empty'        => false,  'fields'            => 'all', 'parent'            => 0, 'hierarchical'      => true, 'child_of'          => 0, 'pad_counts'        => false, 'cache_domain'      => 'core' ); $terms = get_terms($taxonomies, $args); $return .= '<ul class="'.$taxonomies.'">';    foreach ( $terms as $term ) { $subterms = get_terms($taxonomies, array( 'parent'   => $term->term_id, 'hide_empty' => false )); $has_sub = ""; if( is_array($subterms) && !empty($subterms) ){ $has_sub = " has-children"; if(in_array_r($subterms, 'term_id', $selected_term_open)){ $has_sub .= " open"; } } $checked = ''; if(in_array($term->term_id, $selected_term)){ $checked = 'checked'; } // return terms (working) $return .= sprintf( '<li id="category-%1$s" class="toggle%6$s"><label><input type="%3$s" value="%1$s" name="%4$s" class="%5$s" %7$s><span>%2$s</span></label>', $term->term_id, $term->name, $input_type, $term->taxonomy, $input_class, $has_sub, $checked #7 ); if( is_array($subterms) && !empty($subterms) )        $return .= '<ul class="children">';
foreach ( $subterms as $subterm ) { $checked = ''; if(in_array($subterm->term_id, $selected_term)){ $checked = 'checked'; } $return .= sprintf( '<li id="category-%1$s" class="toggle"><label><input type="%3$s" value="%1$s" name="%4$s" class="%5$s" %6$s><span>%2$s</span></label>', $subterm->term_id, $subterm->name, $input_type, $term->taxonomy, $input_class, $checked # 6 ); $return .= '</li>'; //end subterms li } if( is_array($subterms) && !empty($subterms) )        $return .= '</ul>'; //end subterms ul $return .= '</li>'; //end terms li } //end foreach term $return .= '</ul>'; return $return;}
/** add current page active class */function in_array_r($array, $key, $val) {    foreach ($array as $item){ if (isset($item->$key) && $item->$key == $val){ return true; } } return false;}

WordPress wp_nav_menu() add new custom sub menu item

If some time we need to add new menu item in drop down list. bellow code to we can add sub menu.

See demo image


function dalwadiwp_submenu_item($items, $args) {

$theme_location = 'main-menu';// Theme Location slug
## if ( $args->theme_location == 'main-menu' ) // if we can set menu location then used it.
if ( $args->menu == 19 ) // if we can not set menu location then used direct menu id.
{
// debug($items);
$existing_menu_item_db_id = 701;
$new_menu_item_db_id = 98987; // unique id number
$label = 'Log out';
$url = wp_logout_url(get_permalink());

if ( is_user_logged_in() ) {

// only if user is logged-in, do sub-menu link
$item = array(
'title' => $label,
'menu_item_parent' => $existing_menu_item_db_id,
'ID' => 'log-out',
'db_id' => $new_menu_item_db_id,
'url' => $url,
// 'classes' => array( 'custom-menu-item' )// optionally add custom CSS class
);

$items[] = (object) $item;
}
}
return $items;
}

add_filter('wp_nav_menu_objects', 'dalwadiwp_submenu_item',10 , 2);

 

WordPress remove plugin deactivate link(option) from admin


add_filter( 'plugin_action_links', 'disable_plugin_deactivation', 10, 4 );
function disable_plugin_deactivation( $actions, $plugin_file, $plugin_data, $context ) {


// Remove edit link for all
if ( array_key_exists( 'edit', $actions ) )
unset( $actions['edit'] );


// Remove deactivate link for crucial plugins
if ( array_key_exists( 'deactivate', $actions ) && in_array( $plugin_file, array(
'woocommerce/woocommerce.php',
'contact-form-7/wp-contact-form-7.php'
)))
unset( $actions['deactivate'] );
return $actions;
}

Call jQuery function after all image are load

Some time we need to set equal height in our design. using below snippet we can easily call function or custom code.


// =============================================
// load portfolio list
// =============================================
function load_portfolio_list( post_length ) {

var category_id = jQuery(".portfolio-list").data('category_id');
jQuery( '.portfolio-ajax' ).addClass('loading');
jQuery.ajax({
type: "POST",
url: adminurl,
dataType: 'json',
data: { action : 'load_portfolio', post_length : post_length, category_id : category_id},
success: function (result){
jQuery('.portfolio-list .portfolio-ajax').remove();
jQuery('.portfolio-list .row').append(result.portfolio_list).imagesLoaded().then(function(){
equalheight('.portfilio-item');
});
},
error:function(){
alert("Error: There is some issue please try again.");
},
beforeSend:function(){
jQuery( '.portfolio-ajax' ).addClass('loading');
},
complete: function () {
jQuery( '.portfolio-ajax' ).removeClass('loading');
// Our code after load
}
});
}

below code are check image are loading after done function will return


// Fn to allow an event to fire after all images are loaded
jQuery.fn.imagesLoaded = function ($) {

// get all the images (excluding those with no src attribute)
var $imgs = this.find('img[src!=""]');
// if there's no images, just return an already resolved promise
if (!$imgs.length) {return jQuery.Deferred().resolve().promise();}

// for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)
var dfds = [];
$imgs.each(function(){

var dfd = jQuery.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.onerror = function(){dfd.resolve();}
img.src = this.src;

});

// return a master promise object which will resolve when all the deferred objects have resolved
// IE - when all the images are loaded
return jQuery.when.apply(jQuery,dfds);

}

WordPress file protected with user login

Some time we deed to give option to user download PDF, Doc file the protected with user login

On Download action code as like below


foreach($download_list as $list) {
$title = $list['title'];
$download = $list['download']['url'];

$path = get_home_url().'/';
$dir = '';
$resource_src = str_replace($path, $dir, $download);
$data = base64_encode($resource_src.'^'.get_current_user_id());

$url = get_site_url()."/download.php?file=$data";
?>
<li><a href="<?php echo $url; ?>" target="_blank"><?php echo $title; ?></a></li>
<?php
}

Create “download.php” file from root and add below code.


include('wp-load.php');

if( !get_current_user_id() )
{
wp_redirect(site_url('login/'));
exit;
}
$rew = explode('^',base64_decode($_GET['file']));
if($rew[1] != get_current_user_id())
{
wp_redirect(site_url('login/'));
exit;
}
$file = $rew[0];
$all = $_GET['all'];
if(isset($all)) {
if(json_decode($all)) {
$allFiles = json_decode($all);
} else {
$allFiles = explode(',',$all);

}

$zipname = 'images-'.date('YmdHis').'.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

foreach ($allFiles as $imgfile) {
$path_parts = pathinfo($imgfile);
$ext = strtolower($path_parts["extension"]);
if($ext != 'php') {
$zip->addFile($imgfile, basename($imgfile));
}
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$zipname");
header("Pragma: no-cache");
header("Expires: 0");

readfile($zipname);
unlink($zipname);
}
if(isset($file)) {
download_file($file);
}
function download_file( $fullPath ){

// Must be fresh start
if( headers_sent() )
die('Headers Sent');

// Required for some browsers
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');

// File Exists?
if( file_exists($fullPath) ){

// Parse Info / Get Extension
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);

// Determine Content Type
switch ($ext) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}

if($ext != 'php') {
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile( $fullPath );
} else
die('Invalid File');

} else
die('File Not Found');

}

Good Plug in list for normal WordPress website

For create option in admin page and post
https://github.com/wp-premium/advanced-custom-fields-pro

Regenerate image size
https://wordpress.org/support/plugin/ajax-thumbnail-rebuild/

Autoptimize css and JS file
https://wordpress.org/plugins/autoptimize/

Category and taxonomy reorder
https://wordpress.org/plugins/taxonomy-terms-order/

Custom Post Order
https://wordpress.org/plugins/simple-custom-post-order/
Security
https://wordpress.org/plugins/better-wp-security/
WooCommerce PDF Invoices & Packing Slips
https://wordpress.org/plugins/woocommerce-pdf-invoices-packing-slips/
check cron job schedule
https://wordpress.org/plugins/wp-crontrol/
WP-Mail-SMTP
https://wordpress.org/plugins/wp-mail-smtp/

Set Columns
https://wordpress.org/support/plugin/genesis-easy-columns/reviews/

Stripe payment gateway

https://wordpress.org/plugins/woocommerce-gateway-stripe/

Contact Form DB

https://cfdbplugin.com/

Custom Featured Image Metabox

 

Duplicate Post

https://wordpress.org/plugins/duplicate-post/

SendGrid

https://wordpress.org/plugins/sendgrid-email-delivery-simplified/

The Events Calendar

https://wordpress.org/plugins/the-events-calendar/

W3 Total Cache

https://wordpress.org/plugins/w3-total-cache/

WordPress seo

https://wordpress.org/plugins/wordpress-seo/

YITH WooCommerce Mailchimp

https://wordpress.org/plugins/yith-woocommerce-mailchimp/

WordPress WooCommerce import product with CSV file

When we need to import product data using this script easily add or modified existing product data. also we can download last uploaded CSV file.

add_action( 'admin_menu', 'product_data_admin_menu' );
function product_data_admin_menu() {
	add_submenu_page( 'edit.php?post_type=product','Product import', 'Product import', 'manage_options', 'product_import', 'product_import_admin_section', 'dashicons-analytics', 58  );
}


function product_import_admin_section(){

?>

<div class="wrap parents_import">
	<h2>Product CSV Import</h2>
	<?php 
	
	global $wpdb,$post;
	
	$date = get_option('last_product_import_time');	

	$old_date_timestamp = strtotime($date);
	$new_date = date('Y-m-d h:i', $old_date_timestamp);
	$csv_name = get_option('last_product_import_file');
	
	if(!empty($csv_name)):
		echo '<p>You can <a href="'.get_template_directory_uri().'/csv/'.$csv_name.'" target="_blank" class="blue"><strong>download last upload file </strong></a> for reference.</p>';
		echo '<p> Last uploaded date is '.$new_date.' </p>';
	endif;	

	?>



	<form action="" method="post" id="prodcut_import" enctype="multipart/form-data">	
		<div class="fileUpload ">
			<span>Upload</span>
			<input id="uploadBtn" name="uploadfile" type="file" class="upload" />
		</div>
		<input type="submit" name="submit" class="button button-primary imp-submit-btn" value="Submit">			
		</form>
	</div>

	<?php
	
	
if (isset($_POST['submit'])){
		set_time_limit(0); 
		error_reporting(E_ERROR | E_WARNING | E_PARSE);
		
		if ($_FILES['uploadfile']['size'] != 0)
		{
			
		global $wpdb,$post;
		$filename = $_FILES['uploadfile']['name'];
		$allowed =  array('csv');
		$filename = $_FILES['uploadfile']['name'];
		$fileTmp_name = $_FILES['uploadfile']['tmp_name'];
		$fileData = file($fileTmp_name);
		$user_count = count($fileData);
		$ext = pathinfo($filename, PATHINFO_EXTENSION);
		if(in_array($ext,$allowed) ) {
			
			
			$taxonomy = 'product_cat';
			$taxonomy_brand = 'brand';
			$user_id  = 1;		

			$row = 0;
			$errorData = array();
			$countusers = array();
			if (($handle = fopen($fileTmp_name, "r")) !== FALSE) {
			while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
						
				if($row == 0){ 
					$row++; continue;
				}
				$data = array_map("utf8_encode", $data );
				
				$SKU 				= $data[0]; # Item SKU
				$post_thumb 		= $data[1];	# Product Image
				$post_title 		= $data[2];	# Product Name
				$content 			= $data[3];	# Long Product Description
				$post_content		= (!empty($content)) ? $content : '';
				$price	 			= str_replace('$', '', $data[4]);	#Price
				$price				= preg_replace("/[^0-9\.]/", '', $price);
				$category   		= ucfirst($data[5]);	#Product Category
				$qty   				= $data[6];		#Quantity On Hand
				$stock_status			= ($qty > 0 ) ? 'instock' : 'outofstock';		#Out of Stock / In Stock
				
				$product_slider_temp	= (!empty($data[12]) ? $data[12].',':'');	#Main Image URL
				$product_slider_temp1	= $data[13];	#Product Gallery URL(s)
				
				$product_slider		= $product_slider_temp.$product_slider_temp1;
				$brand	= ucfirst($data[14]);	#Brand
				
				$distributor_a = array('regular_price'=>$distributor_discount_a,'selling_price'=>'');
				$distributor_b = array('regular_price'=>$distributor_discount_b,'selling_price'=>'');
				$distributor_c = array('regular_price'=>$distributor_discount_c,'selling_price'=>'');
				
				
				$SKUD = wc_get_product_id_by_sku($SKU);
				if($SKUD == 0){
					$my_post = array(
						'post_author' 	=> $user_id,
						'post_title'    => $post_title,
						'post_name'     => $post_title,
						'post_content'  => '',
						'post_status'   => 'publish',
						'post_type'     => 'product'
					);
								
					$lastPostid = wp_insert_post( $my_post, $wp_error );
					$ID = $lastPostid;
					if(!empty($post_thumb)){
						Generate_Featured_Image($post_thumb, $ID);
					}
					update_post_meta( $ID, '_visibility', 'visible' );
					update_post_meta( $ID, '_wpr_cp', 'no' );
					update_post_meta( $ID, '_edit_last', 1 );
					update_post_meta( $ID, '_downloadable', 'no' );
					update_post_meta( $ID, 'total_sales', 0 );
					update_post_meta( $ID, '_virtual', 'no' );
					update_post_meta( $ID, '_purchase_note', '' );
					update_post_meta( $ID, '_featured', 'no' );
					update_post_meta( $ID, '_weight', '' );
					update_post_meta( $ID, '_length', '' );
					update_post_meta( $ID, '_width', '' );
					update_post_meta( $ID, '_height', '' );
					update_post_meta( $ID, '_product_attributes', 'a:0:{}' );
					update_post_meta( $ID, '_sale_price_dates_from', '' );
					update_post_meta( $ID, '_sold_individually', '' );
					update_post_meta( $ID, '_manage_stock', 'yes' );
					update_post_meta( $ID, '_backorders', 'no' );
					update_post_meta( $ID, '_upsell_ids', 'a:0:{}' );
					update_post_meta( $ID, '_crosssell_ids', 'a:0:{}' );
					update_post_meta( $ID, '_product_version', '2.5.6' );
					update_post_meta( $ID, '_product_image_gallery', '' ); 
					
					if(!empty($category)){
						wp_set_object_terms( $ID, $category, $taxonomy, true );	
					}
					
					
					if(!empty($price)){
						update_post_meta( $ID, '_price', $price );
						update_post_meta( $ID, '_regular_price', $price  );		 
					}
					
					if(!empty($qty)){
						update_post_meta( $ID, '_stock', $qty  );
					}
					if(!empty($stock_status)){
						update_post_meta( $ID, '_stock_status', $stock_status  );
					}
					
					if(!empty($SKU)){
						update_post_meta( $ID, '_sku', $SKU  );
					}
					
					if(!empty($brand)){
						wp_set_object_terms( $ID, $brand, $taxonomy_brand, true );	
					}						
					
				}
				else{
					$SID = $SKUD;		
					$my_post = array(
						'ID'           => $SID,
						'post_title'    => $post_title,
						'post_name'     => $post_title,
						'post_content'  => '',
						'post_status'   => 'publish',
						'post_type'     => 'product'
					);
							
					$lastPostid = wp_insert_post( $my_post, $wp_error );
					
					if(!empty($post_thumb)){
						Generate_Featured_Image($post_thumb,$SID);
					}
					if(!empty($category)){
						wp_set_object_terms( $SID, $category, $taxonomy, true );	
					}
					
					if(!empty($price)){
						update_post_meta( $SID, '_price', $price );
						update_post_meta( $SID, '_regular_price', $price  );		 
					}
					
					if(!empty($qty)){
						update_post_meta( $SID, '_stock', $qty  );
					}
					if(!empty($stock_status)){
						update_post_meta( $SID, '_stock_status', $stock_status  );
					}
					
					
					if(!empty($brand)){
						wp_set_object_terms( $SID, $brand, $taxonomy_brand, true );	
					}
				}	
			}	## while end		
			fclose($handle);
			} 	## if (($handle = fopen($fileTmp_name, "r")) !== FALSE) {
			
	
		
		  
			  
	   echo '<div class="notice notice-success is-dismissible">';
	   echo '<p><strong>Import data successfully.</strong></p>';
	   echo '</div>';
			
		$CurrentDate = date('j-m-y-h-i');
		$CurrentDateSave = date('Y-m-d h:i');
		$newname = "product_date-".$CurrentDate.".".$ext; 
		$target = get_template_directory().'/csv/'.$newname;
		
		if (!file_exists(get_template_directory().'/csv/')) {
			mkdir(get_template_directory().'/csv/', 0777, true);
		}
		move_uploaded_file($_FILES['uploadfile']['tmp_name'],$target);
		
		add_option( 'last_product_import_file', $newname, '', 'yes' );
		add_option( 'last_product_import_time', $CurrentDateSave, '', 'yes' );

		}
		else{
			echo '<div class="notice notice-warning is-dismissible">';
			echo '<p><strong>Please upload csv file only.</strong></p>';
			echo '</div>';
		}
		
	} // Empty check
	else{
			echo '<div class="notice notice-warning is-dismissible">';
			echo '<p><strong>Please upload file.</strong></p>';
			echo '</div>';
		}
	}// upload action
}