Month: May 2017

WordPress search Post(news) with ajax

js code


/* All filter news and pagination*/
jQuery('.news-filter .categoryCheck').on( 'change' , function() {
if(!jQuery(this).val()){
jQuery('.news-filter .categoryCheck').prop( "checked", false );
}
load_news_list(0,1);
});

jQuery('.search-btn').on( 'click' , function() {
load_news_list(0,1);
});
jQuery('#srch_keyword').on('keypress', function(e){
if(e.keyCode == '13'){
e.preventDefault();
load_news_list(0,1);
}
});
jQuery('.pagination').on( 'click', '.page-numbers', function( event ) {
event.preventDefault();
page = find_page_number(jQuery(this));
var post_length = jQuery( '.news-div' ).length;
load_news_list( post_length, page);
});

 

/* load news list */
function load_news_list(post_length, page) {

var news_cats = jQuery('.categoryCheck:checked').map(function() {return this.value;}).get().join(',');
var year = ( jQuery( '#year' ).length > 0 ) ? jQuery( '#year' ).val() : '';
var monthnum = ( jQuery( '#monthnum' ).length > 0 ) ? jQuery( '#monthnum' ).val() : '';
var search_val = jQuery('#srch_keyword').val();
// jQuery( '.clear-all' ).css( 'display' , 'none' );
if( news_cats.length > 0 ) {
jQuery( '.clear-all' ).css( 'display' , 'inline-block' );
}

jQuery.ajax({
type: "POST",
url: adminurl,
data: { action : 'load_news', news_cats: news_cats, post_length : post_length, year: year, monthnum: monthnum ,search:search_val, page: page},
success: function (result){
var responseData = JSON.parse(result);
jQuery( '.load-more-news' ).remove();
jQuery( '.news-listing' ).empty();
jQuery( '.news-listing' ).append(responseData.news);
jQuery( '.pagination' ).empty()
jQuery( '.pagination' ).append(responseData.pagination);
},
error:function(){
alert("Error: There is some issue please try again.");
},
beforeSend:function(){
jQuery( '.load-result' ).css( 'display' , 'block' );
},
complete: function () {
jQuery( '.load-result' ).css( 'display' , 'none' );
}
});
}

 

WordPress code


add_action( 'wp_ajax_nopriv_load_news', 'load_news' );
add_action( 'wp_ajax_load_news', 'load_news' );
function load_news() {
$per_page = 12;
$paged = ( isset($_POST['page']) ) ? $_POST['page'] : 1 ;
$offset = (( $paged - 1 ) * $per_page);
/* if( !empty( $_POST['post_length'] ) ) { */
$post_length = $_POST['post_length'];
//$offset = $post_length;
$nextOffset = $offset + $per_page;
/* } */
$result = '';

$pagination = '';
$newsList = getNewsArray( $offset , $per_page , $_POST );

$result = '<div class="col-sm-12"><header class="page-header">';
$result .= '<h2 class="page-title">Sorry, it seems that we didn&rsquo;t find any results</h2>';
$result .= '</header>';
$result .= '<div class="page-content">';
$result .= '<p>Please try the search function at the top of the page to see if you can find what you&rsquo;re looking for</p>';
$result .= '</div></div>';
if ( $newsList->have_posts() ) {
$result = '';
while ( $newsList->have_posts() ) { $newsList->the_post();
$result .= post_html( $post->ID );
}
}

if($newsList->max_num_pages > 0){
$big = 999999999;
$pagination = paginate_links( array(
'type' => 'plain',
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, $paged ),
'total' => $newsList->max_num_pages,
'prev_next' => true,
'prev_text' => 'Prev',
'next_text' => 'Next',
) );
//$pagination .= football_pagination($newsList->max_num_pages);

} else {
$result .= '<div class="no-more-news"></div>';
}

$data['news'] = $result;
$data['pagination'] = $pagination;
echo json_encode( $data );

die();
}

&nbsp;
function getNewsArray( $offset , $per_page , $newsFilter ) {

$argsNews = array('post_type' => 'post', 'post_status'=> 'publish' , 'posts_per_page' => $per_page , 'offset' => $offset, 'order' => 'desc', 'orderby' => 'date' );

if( !empty($newsFilter['news_cats']) ) {
$cats = explode( ',' , $newsFilter['news_cats'] );
$argsNews['category__in'] = $cats;
}
if(!empty($newsFilter['year'])){
$argsNews['year'] = $newsFilter['year'];
}
if(!empty($newsFilter['monthnum'])){
$argsNews['monthnum'] = $newsFilter['monthnum'];
}
if(!empty($newsFilter['search'])){
$argsNews['s'] = $newsFilter['search'];
}
$newsList = new WP_Query( $argsNews );

return $newsList;
}

 

 

Advertisements

WordPress pagination with custom MySQL query

Simple pagination with custom query


$per_page = 50; # Set per page
$paged = ( get_query_var('paged') != 0 ) ? get_query_var('paged') : 1 ; ## get paged number
$offset = (( $paged - 1 ) * $per_page); ## set offset

$trial_list = football_trial_list(null, $offset, $per_page);

$trial_total = football_trial_list(null,0,-1);
$total = count($trial_total);

$max_num_pages = ceil( $total / $per_page );

$pagination = football_pagination($max_num_pages);

function football_trial_list($post_id = null, $offset = 0, $per_page = 3, $request = null){
global $wpdb;
$user_id = get_current_user_id();
$table_team = $wpdb->prefix . 'trial';

$distance = "";
if(isset($request) && !empty($request)){
if(isset($request['post_code']) && !empty($request['post_code'])){

$address_data = football_get_latitude_longitude($request['post_code']);
$lat = $address_data['lat'];
$lng = $address_data['lng'];

$distance = ", ( 3959 * acos( cos( radians(".$lat.") ) * cos( radians( tr.lat ) ) * cos( radians( tr.lng ) - radians(".$lng.") ) + sin( radians(".$lat.") ) * sin( radians( tr.lat ) ) ) ) AS distance";
}
}

$query = "SELECT tr.*, p.post_title, p.post_content $distance FROM $table_team AS tr ";
$query .= " INNER JOIN ".$wpdb->prefix."posts AS p ON ( tr.post_id = p.ID ) ";
$query .= " WHERE p.post_type = 'trials' AND p.post_status = 'publish' ";

// if get single post data
if(!empty($post_id) && $post_id != null){
$query .= " AND p.ID = $post_id ";
}

if(isset($request) && !empty($request)){
// if(isset($request['post_code']) && !empty($request['post_code'])){
// $query .= " AND tr.postcode LIKE '%".$request['post_code']."%'";
// }

if(isset($request['trial_name']) && !empty($request['trial_name'])){
$query .= " AND p.post_title LIKE '%".$request['trial_name']."%'";
}
if(isset($request['trial_age']) && !empty($request['trial_age'])){
if($request['trial_age'] >= 35)
$query .= " AND tr.trial_age >= ".$request['trial_age']."";
else
$query .= " AND tr.trial_age <= ".$request['trial_age']."";
}

// if(!empty($request['post_code']) && !empty($request['distance_min']) && !empty($request['distance_max'])){
if(!empty($request['post_code'])){
$query .= " HAVING distance BETWEEN ".$request['distance_min']." AND ".$request['distance_max']." ";
}

// Upcoming Trials
if(isset($request['upcoming']) && $request['upcoming'] = true){
$query .= " AND tr.trial_date >= CURDATE()";
}
}
else{
$query .= " AND tr.user_id = $user_id ";
}

// Upcoming Trials
if(isset($request['upcoming']) && $request['upcoming'] = true)
$query .= " ORDER BY tr.trial_date ASC ";
else
$query .= " ORDER BY p.post_date DESC ";

if($per_page != -1){
$query .= " LIMIT $offset, $per_page";
}

// echo $query; #die;
return $wpdb->get_results( $query, OBJECT );
}
// =============================================
// Default pagination
// =============================================
function football_pagination($max_num_pages){

if($max_num_pages > 1){
$big = 999999999;
$pagination = "<div class='toolbar'>";
$pagination .= paginate_links( array(
'type' => 'list',
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $max_num_pages,
'prev_next' => true,
'prev_text' => 'Prev',
'next_text' => 'Next',
) );
$pagination .= "</div>";

return $pagination;
}
else{
return '';
}
}

 

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;
}

jQuery equal height based on rows listing


// =========================
// Equal height of Box base design.
// =========================
equalheight = function (container) {
var currentTallest = 0,
currentRowStart = 0,
rowDivs = new Array(),
jQueryel,
topPosition = 0;
jQuery(container).each(function () {
jQueryel = jQuery(this);
jQuery(jQueryel).height('auto')
topPostion = jQueryel.position().top;

if (currentRowStart != topPostion) {
for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
rowDivs.length = 0; // empty the array
currentRowStart = topPostion;
currentTallest = jQueryel.height();
rowDivs.push(jQueryel);
} else {
rowDivs.push(jQueryel);
currentTallest = (currentTallest < jQueryel.height()) ? (jQueryel.height()) : (currentTallest);
}
for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
});
}

// =========================
// Call Equal height function
// =========================
jQuery(window).load(function() {
equalheight('.class_name');
});
jQuery(window).resize(function(){
equalheight('.class_name');
});

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');

}