Load More posts feature in WordPress

Copy below code into your functions.php


function misha_paginator( $first_page_url ){

// the function works only with $wp_query that's why we must use query_posts() instead of WP_Query()
global $wp_query;

// remove the trailing slash if necessary
$first_page_url = untrailingslashit( $first_page_url );


// it is time to separate our URL from search query
$first_page_url_exploded = array(); // set it to empty array
$first_page_url_exploded = explode("/?", $first_page_url);
// by default a search query is empty
$search_query = '';
// if the second array element exists
if( isset( $first_page_url_exploded[1] ) ) {
$search_query = "/?" . $first_page_url_exploded[1];
$first_page_url = $first_page_url_exploded[0];
}

// get parameters from $wp_query object
// how much posts to display per page (DO NOT SET CUSTOM VALUE HERE!!!)
$posts_per_page = (int) $wp_query->query_vars['posts_per_page'];
// current page
$current_page = (int) $wp_query->query_vars['paged'];
// the overall amount of pages
$max_page = $wp_query->max_num_pages;

// we don't have to display pagination or load more button in this case
if( $max_page <= 1 ) return;

// set the current page to 1 if not exists
if( empty( $current_page ) || $current_page == 0) $current_page = 1;

// you can play with this parameter - how much links to display in pagination
$links_in_the_middle = 4;
$links_in_the_middle_minus_1 = $links_in_the_middle-1;

$first_link_in_the_middle = $current_page - floor( $links_in_the_middle_minus_1/2 );
$last_link_in_the_middle = $current_page + ceil( $links_in_the_middle_minus_1/2 );

// some calculations with $first_link_in_the_middle and $last_link_in_the_middle
if( $first_link_in_the_middle <= 0 ) $first_link_in_the_middle = 1;
if( ( $last_link_in_the_middle - $first_link_in_the_middle ) != $links_in_the_middle_minus_1 ) { $last_link_in_the_middle = $first_link_in_the_middle + $links_in_the_middle_minus_1; }
if( $last_link_in_the_middle > $max_page ) { $first_link_in_the_middle = $max_page - $links_in_the_middle_minus_1; $last_link_in_the_middle = (int) $max_page; }
if( $first_link_in_the_middle <= 0 ) $first_link_in_the_middle = 1;

// begin to generate HTML of the pagination
$pagination = '<nav id="misha_pagination" class="navigation pagination" role="navigation">
<div class="older">';

if( $current_page < $max_page )
$pagination.= '<a title="Read More" id="misha_loadmore">Read More <i class="fa fa-angle-double-right"></i> </a> ';
$pagination.= "</div></nav>\n";
echo str_replace(array("/page/1?", "/page/1\""), array("?", "\""), $pagination);
}
function misha_my_load_more_scripts() {
global $wp_query;
// In most cases it is already included on the page and this line can be removed
wp_enqueue_script('jquery');

// register our main script but do not enqueue it yet
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/myloadmore.js', array('jquery') );

wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
'first_page' => get_pagenum_link(1)
) );

wp_enqueue_script( 'my_loadmore' );
}

add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );

function misha_loadmore_ajax_handler(){

$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
query_posts( $args );

if( have_posts() ) :
while( have_posts() ): the_post();
get_template_part('content', 'grid');
endwhile;

endif;
die;
}

add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}

 

JS code to send Ajax call and recieve response

<script type="text/javascript">
jQuery(function($){
$('body').on('click', '#misha_loadmore', function(){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data : {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page,
'first_page' : misha_loadmore_params.first_page // here is the new parameter
},
type : 'POST',
beforeSend : function ( xhr ) {
$('#misha_loadmore').text('Loading...');
},
success : function( data ){
$('ul.sp-grid').append(data);
//$('#misha_pagination').remove();
$('#misha_loadmore').html('Read More <i class="fa fa-angle-double-right"></i>');
misha_loadmore_params.current_page++;
}
});
return false;
});
});
</script> 

 

Finally html button which will be clicked to load more posts again and again.

<?php misha_paginator( get_pagenum_link() ); ?>

Custom Audio Player with Jquery

Css for audio player

*css for audio player*/
/* Absolute Center */
.abs-center{
  margin: auto;
  position: fixed;
  top:0; right:0; bottom:0; left:0;
}
/*Container for audio player*/
#audioplayer{
  height: 60px;
  margin: auto;
  margin-top: 50px;
}
/* Play/Pause Button */
#pButton{
  height:30px;
  width: 20px;
  border: none;
  background-size: 50% 50%;
  background-repeat: no-repeat;
  background-position: center;
  float:left;
  outline:none;

}
/*Classes for play/pause button background*/
.play{background: url('../images/play-new.png') ;}
.pause{background: url('../images/pause-new.png') ;}

.timeline{
  background: rgba(0, 0, 0, 0.3) none repeat scroll 0 0;
    border-radius: 0px;
    float: left;
    height: 1px;
    margin-top: 14px;
    width: 226px;
}

.section-70 .timeline{width: 168px;}

/*Grabable Playhead*/
.playhead{
  background: #ccc none repeat scroll 0 0;
    border-radius: 0;
    cursor: pointer;
    height: 12px;
    margin-top: -6px;
    width: 1px;
}

HTML part

<div id="wrapper">
  <div id="audioplayer" class="player-6">
    <button id="pButton" class="play"></button>
    <audio class="music" preload="true">
      <source src="mp3/challa.mp3">
    </audio>
    <div class="timeline">
      <div class="playhead"></div>
    </div>
  </div>
</div>

JQuery Part

/*document.addEventListener("DOMContentLoaded", function(event) {

var music = document.getElementById('music'); // id for audio element
var duration; // Duration of audio clip

var pButton = document.getElementById('pButton');

var playhead = document.getElementById('playhead'); // playhead
var timeline = document.getElementById('timeline'); // timeline

// timeline width adjusted for playhead
var timelineWidth = timeline.offsetWidth - playhead.offsetWidth;

// play button event listenter
pButton.addEventListener("click", play);

// timeupdate event listener
music.addEventListener("timeupdate", timeUpdate, false);

// makes timeline clickable
timeline.addEventListener("click", function(event) {
    moveplayhead(event);
    //music.currentTime = parseFloat(duration * clickPercent(event));
    console.log(duration * clickPercent(event));
}, false);

// returns click as decimal (.77) of the total timelineWidth
function clickPercent(event) {
    return (event.clientX - getPosition(timeline)) / timelineWidth;

}

// makes playhead draggable
playhead.addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);

// Boolean value so that audio position is updated only when the playhead is released
var onplayhead = false;

// mouseDown EventListener
function mouseDown() {
    onplayhead = true;
    window.addEventListener('mousemove', moveplayhead, true);
    music.removeEventListener('timeupdate', timeUpdate, false);
}

// mouseUp EventListener
// getting input from all mouse clicks
function mouseUp(event) {
    if (onplayhead == true) {
        moveplayhead(event);
        window.removeEventListener('mousemove', moveplayhead, true);
        // change current time
        music.currentTime = parseFloat(duration * clickPercent(event));
        music.addEventListener('timeupdate', timeUpdate, false);
    }
    onplayhead = false;
}
// mousemove EventListener
// Moves playhead as user drags
function moveplayhead(event) {
    var newMargLeft = event.clientX - getPosition(timeline);

    if (newMargLeft >= 0 && newMargLeft <= timelineWidth) {
        playhead.style.marginLeft = newMargLeft + "px";
    }
    if (newMargLeft < 0) {
        playhead.style.marginLeft = "0px";
    }
    if (newMargLeft > timelineWidth) {
        playhead.style.marginLeft = timelineWidth + "px";
    }
}




// Gets audio file duration
music.addEventListener("canplaythrough", function() {
    duration = music.duration;
}, false);




});*/


$(document).ready(function(){
    $('.play').bind('click', function() {
        play(this,$(this).next('audio'),$($(this)[0].parentElement).find('.timeline'));          
    });     

    //Play and Pause
    function play(button,music,timeline) {
        // makes timeline clickable
        $(timeline).bind('click', function() {
            moveplayhead(event,$(this).find('.playhead'),timeline);
            var timelineWidth = $(timeline).outerWidth() - $($(this).find('.playhead')).outerWidth();
            music.currentTime = parseFloat(music.duration * clickPercent(event,timeline,timelineWidth));            
        });

        music[0].addEventListener("timeupdate", timeUpdate, false);
        music[0].timelineWidth = 200;
        music[0].currentTime = music[0].currentTime;
        music[0].duration = music[0].duration;


        if (music[0].paused) {
            music[0].play();
            // remove play, add pause
            $(button).removeClass('play');
            $(button).addClass('pause');
        } else { // pause music
            music[0].pause();
            // remove pause, add play            
            $(button).removeClass('pause');
            $(button).addClass('play');
        }
    }


    function moveplayhead(event,playhead,timeline) { 
        var newMargLeft = event.clientX - getPosition(timeline);

        var timelineWidth = timeline.offsetWidth - playhead.offsetWidth;

        if (newMargLeft >= 0 && newMargLeft <= timelineWidth) {
            playhead.style.marginLeft = newMargLeft + "px";
        }
        if (newMargLeft < 0) {
            playhead.style.marginLeft = "0px";
        }
        if (newMargLeft > timelineWidth) {
            playhead.style.marginLeft = timelineWidth + "px";
        }
    }


    function getPosition(el) {
        return $(el)[0].getBoundingClientRect();
    }

    function clickPercent(event,timeline,timelineWidth) {        
        return (event.clientX - getPosition(timeline)) / timelineWidth;
    }

    // timeUpdate
    // Synchronizes playhead position with current point in audio
    function timeUpdate(evt) {
        var playPercent = evt.target.timelineWidth * (evt.target.currentTime / evt.target.duration);
        $($($(this)[0].parentElement).find('.timeline')).find('.playhead').css("margin-left",playPercent + "px");
    }
 
});

Image Read, upload with JS as Blob in Database and show on page

<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

if(isset($_POST['image']) && $_POST['image']=='upload')
{
    $image = $_POST['string'] ;
    $sql = "INSERT INTO  image (name, image)
    VALUES ('image_name','".$image."')";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

}

?>

<HTML>
<HEAD>
<TITLE>Read image in JS</TITLE>
<style>
   #inputTextToSave {
        width:512px; 
        height:256px;
      }

      #holder { 
        border: 10px dashed #ccc; 
        width: 300px; 
        height: 300px; 
      }

      #holder.hover { 
        border: 10px dashed #333; 
      }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</HEAD>
<BODY>
<table>

      <tr>
        <td colspan="3">Binary data:</td>
      </tr>

      <tr>
        <td colspan="3">
          <textarea id="inputTextToSave"></textarea>
        </td>
      </tr>

      <tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs" /></td>
        <td><button onclick="saveImage()">Save file</button></td>
      </tr>

      <tr>
        <td>Select a File to Load:</td>
        <td><input type="file" id="fileToLoad" /></td>
          <td><button onclick="loadImage()">Load file</button></td>
      </tr>

      <tr>
        <td colspan="3" id="imagePreview">
        </td>
      </tr>

    </table>

<script>
var contentType = '';

      function destroyClickedElement(event) {
        document.body.removeChild(event.target);
      }

      window.loadImage = function() {
        var file = document.getElementById("fileToLoad").files[0];

        var reader = new FileReader();
        reader.onload = function(event) {
          var data = event.target.result;
          document.getElementById("inputTextToSave").value = data;

          var imagePreview = document.getElementById("imagePreview");
          imagePreview.innerHTML = '';

          var dataURLReader = new FileReader();
          dataURLReader.onload = function(event) {
            // Parse image properties
            var dataURL = event.target.result;
            $.post( "image_read_in_js.php", 
                { 
                    "image": "upload",
                    "string":dataURL 
                 },
                function( data ) {
              console.log( data);
            }, "json");
            contentType = dataURL.split(",")[0].split(":")[1].split(";")[0];

            var image = new Image();
            image.src = dataURL;
            image.onload = function() {
              console.log("Image type: " + contentType);
              console.log("Image width: " + this.width);
              console.log("Image height: " + this.height);
              imagePreview.appendChild(this);
            };
          };
          dataURLReader.readAsDataURL(file);


        };
        reader.readAsBinaryString(file);
      }
  
</script>

<div style="border: solid 1px;">
<?php
$sql = "SELECT * FROM image";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo '<img src="' .$row['image'] . '" />';
    }
} else {
    echo "0 results";
}

?>
</div>
</BODY>
</HTML>

Cross domain ajax request to a json file using JSONP

jQuery.ajax({
dataType: "jsonp",
url: https://digimantralabs.com/cishopify/shop/getdata?callback=somefunction,
data: {pid: productID},
success: function(data) { console.log(data);
jQuery('#product_review').html(data);
},
onComplete: function(htmldata){
alert();
}
});

 

$callback =  $this->input->get('callback');
$object=array('postalcodes'
=>array(
array(
"adminName2" => "Westchester",
"adminCode2" => "119",
"postalcode" => "10504",
"adminCode1" => "NY",
"countryCode" => "US",
"lng" => -73.700942,
"placeName" => "Armonk",
"lat" => 41.136002,
"adminName1" => "New York"
)));
echo $callback.'('.json_encode($object).')';

jquery validate plugin on dynamic form inputs not working


$("#coach-profile form").validate({
        rules: {
            "signupcoachform-zip":{
                required:true
            }
        },
        messages: {
            "Activity[activity_id][]": "At least one Activity must be selected",
        },
        errorPlacement: function(error,element){
   
        }
    });

below code needs to be in loop where your dynamic fields are genrated with JS

$('input[name="dynamic_field[activity_&_insurance]['+ activity_id +'][from]"]').rules("add", {
            required: true
        });
        
        $('input[name="dynamic_field[activity_&_insurance]['+ activity_id +'][to]"]').rules("add", {
            required: true
        });

jquery validate error message, mobile phone , url validations

$("#host-profile form").validate({
        rules: {
            "dynamic_field[host_type]":{
                required: true
            },
            "SignupHostForm[mobile]":{
                required:true,
                minlength:10,
                maxlength:10,
                number: true
            },
            "SignupHostForm[gender]":{
                required:true
            },
            "dynamic_field[primary_phone]":{
                required:true,
                minlength:10,
                maxlength:10,
                number: true
            },
            "dynamic_field[alternate_phone]":{
                required:true,
                minlength:10,
                maxlength:10,
                number: true
            },
            "dynamic_field[business_type]":{
                required: true
            },
            "dynamic_field[business_since]":{
                required: true
            },            
            "dynamic_field[place_name]":{
                required: true
            },
            "dynamic_field[business_location]":{
                required: true,
                number: true
            },
            "dynamic_field[company_email]":{
                required: true,
                email: true
            },
            "dynamic_field[website]":{
                required: true,
                url: true
            }, 
            "SignupHostForm[username]":"required",
            "SignupHostForm[zip]":"required",
            "dynamic_field[description]":"required",
            "Activity[activity_id][]":"required",
            "activity_&_insurance][][from]":"required",
            "activity_&_insurance][][to]":"required",
            
            "dynamic_field[place_address2]":"required",
            "dynamic_field[place_postal_code]":{
                required: true,
                number: true
            },
            "dynamic_field[intro_blurb]": "required",
            "dynamic_field[qualifications_&_affiliations]": "required",
            //"UploadForm[imageFiles][profile_image]": "required",
            "Activity[activity_id][]": "required",
            "AvailablilitySchedule[working_day_id][]": "required",
        },
        messages: {
            "Activity[activity_id][]": "At least 1 Activity must be specified",
            "dynamic_field[website]":{
                required: "this is required",
                url: "validate url"
            }
        },
        errorPlacement: function(error,element){
                switch(element.attr("name")){
                    case "UploadForm[imageFiles][profile_image]" : 
                            error.insertAfter('#btn-select1');
                            break;
                    case "Activity[activity_id][]" :
                            error.insertBefore($(element).parents('.activities_list'));
                            break;
                    case "dynamic_field[account_number]" : 
                            $('.place-modal-forms form #host_acc_err').html(error);
                            break;
                    case "dynamic_field[routing_number]" : 
                            $('.place-modal-forms form #host_routing_err').html(error);
                            break;
                    case "attest_check" : 
                            error.insertAfter('#attest_check_span');
                            break;  
                    case "review_check" : 
                            error.insertAfter('#review_check_span');    
                            break;                      
                    default :
                            error.insertAfter(element); 
                            break;
                }
        }
    });