Friday, 15 March 2019

How to Make a WordPress Settings Autocomplete Field Using Ajax


Please put this code in functions.php file.


add_action( 'admin_enqueue_scripts', function() { 
wp_enqueue_script('suggest-js', get_stylesheet_directory_uri().'/js/suggest.js', array( 'suggest' ), '1.0', true );
});

Create suggest.js in theme folder and put this code in suggest.js file

(function(window, document, $, undefined){

var hpadmin = {};

  hpadmin.init = function() {

    $('#blogs_creators').suggest( window.ajaxurl + "?action=ajax-tag-search&tax=category", {multiple:true, multipleSep: ","});

  }

  hpadmin.init();

})(window, document, jQuery);

jQuery('#blogs_creators').suggest( window.ajaxurl + "?action=hwp_ajax_page_search", {multiple:true, multipleSep: ","})


Note: #blogs_creators is a settings custom field id.

Now put this code also in functions.php file.

add_action( 'wp_ajax_hwp_ajax_page_search', function() {

            $s = wp_unslash( $_GET['q'] );

            $comma = _x( ',', 'page delimiter' );
            if ( ',' !== $comma )
                $s = str_replace( $comma, ',', $s );
            if ( false !== strpos( $s, ',' ) ) {
                $s = explode( ',', $s );
                $s = $s[count( $s ) - 1];
            }
            $s = trim( $s );

            $term_search_min_chars = 2;

            $the_query = new WP_Query( 
                array( 
                    's' => $s,
                    'posts_per_page' => 5,
                    'post_type' => 'page'
                    ) 
                );

            if ( $the_query->have_posts() ) {
                while ( $the_query->have_posts() ) {
                    $the_query->the_post();
                    $results[] = get_the_title();
                }
                /* Restore original Post Data */
                wp_reset_postdata();
            } else {
                $results = 'No results';
            }

            echo join( $results, "\n" );
            wp_die();
});


Reference Link

Tuesday, 1 March 2016

How to call restful api from javascript or hit rest api URL from javascript.

What is REST api?
REST stands for Representational State Transfer. (It is sometimes spelled "ReST".) It relies on a stateless, client-server, cacheable communications protocol and in virtually all cases, the HTTP protocol is used. REST is an architecture style for designing networked applications. 
 Use following code to hit rest api url from javascript and it returns  in json format.
 var myJSONData = {"key1":"value1","key2":"value2","key3":"value3"};

    $.ajax({
            type: 'POST',
            url: 'https://example.com/ttm/subscribe-service',//rest api url
            data: myJSONData,
            dataType: 'application/json',
            success: function(data) { 
             alert("request posted to the sever successfully");
             $('#message').html('<h1>POSTED</h1>');     
          } // Success Function end
          });   // Ajax Call end

Saturday, 13 February 2016

How to get meta keywords and description of a web page?

get_meta_tags() function return all meta tags of web page.
For example:
$url = "http://www.example.com";   
$tags = get_meta_tags($url);
$description     = $tags["description"];
$keywords         = $tags["keywords"];
echo 'Keywords: '.$keywords;
echo '<br/>';
echo 'Description: '.$description;

How to get title of website via website url?

The Title of website can get via site url by using file_get_contents() and php Simple html DOM parser.
php Simple html DOM parser is useful for php deveopers because php developers can easily find DOM elements of web page using php.

Getting title with file_get_contents()
<?php
function get_title($url){
  $str = file_get_contents($url);
  if(strlen($str)>0){
    $str = trim(preg_replace('/\s+/', ' ', $str));
    preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title);
    return $title[1];
  }
}
//For Example:
echo get_title("http://www.example.com/");
?>

Getting title with php Simple html DOM parser
// Include the library
include('simple_html_dom.php');
/ Retrieve the DOM from a given URL
$html = file_get_html('http://www.example.com/');
// Find title tag
$titleTag        = $html->find('title',0)->innertext;
echo 'Ttile: '.$titleTag;

Sunday, 10 January 2016

How can I set the heigh of the iFrame explicitly.

<p>top</p>
<p>
   <iframe id="copayCard" src="https://staging.epower.amadeus.com/Baabtravel/#Page=Flight" scrolling="no" seamless="seamless" style="border: 1px; padding: 0; overflow:hidden;"></iframe>
</p>
<p>bottom</p>
<!-- How can I set the heigh of the iFrame given its $('#eVIEW').attr('height') value?-->
/*! iFrame Resizer (iframeSizer.min.js ) - v2.7.1 - 2014-12-12
 *  Desc: Force cross domain iframes to size to content.
 *  Requires: iframeResizer.contentWindow.min.js to be loaded into the target frame.
 *  Copyright: (c) 2014 David J. Bradshaw - dave@bradshaw.net
 *  License: MIT
 */
 !function(){"use strict";function a(a,b,c){"addEventListener"in window?a.addEventListener(b,c,!1):"attachEvent"in window&&a.attachEvent("on"+b,c)}function b(){var a,b=["moz","webkit","o","ms"];for(a=0;a<b.length&&!w;a+=1)w=window[b[a]+"RequestAnimationFrame"];w||c(" RequestAnimationFrame not supported")}function c(a){y.log&&"object"==typeof console&&console.log(s+"[Host page"+u+"]"+a)}function d(a){function b(){function a(){h(B),f(),y.resizedCallback(B)}k("Height"),k("Width"),i(a,B,"resetPage")}function d(a){var b=a.id;c(" Removing iFrame: "+b),a.parentNode.removeChild(a),y.closedCallback(b),c(" --")}function j(){var a=A.substr(t).split(":");return{iframe:document.getElementById(a[0]),id:a[0],height:a[1],width:a[2],type:a[3]}}function k(a){var b=Number(y["max"+a]),d=Number(y["min"+a]),e=a.toLowerCase(),f=Number(B[e]);if(d>b)throw new Error("Value for min"+a+" can not be greater than max"+a);c(" Checking "+e+" is in range "+d+"-"+b),d>f&&(f=d,c(" Set "+e+" to min value")),f>b&&(f=b,c(" Set "+e+" to max value")),B[e]=""+f}function l(){var b=a.origin,d=B.iframe.src.split("/").slice(0,3).join("/");if(y.checkOrigin&&(c(" Checking connection is from: "+d),""+b!="null"&&b!==d))throw new Error("Unexpected message received from: "+b+" for "+B.iframe.id+". Message was: "+a.data+". This error can be disabled by adding the checkOrigin: false option.");return!0}function m(){return s===(""+A).substr(0,t)}function n(){var a=B.type in{"true":1,"false":1};return a&&c(" Ignoring init message from meta parent page"),a}function o(){var a=A.substr(A.indexOf(":")+r+6);c(" MessageCallback passed: {iframe: "+B.iframe.id+", message: "+a+"}"),y.messageCallback({iframe:B.iframe,message:JSON.parse(a)}),c(" --")}function q(){if(null===B.iframe)throw new Error("iFrame ("+B.id+") does not exist on "+u);return!0}function w(){var a=B.iframe.getBoundingClientRect();return e(),{x:Number(a.left)+Number(v.x),y:Number(a.top)+Number(v.y)}}function x(a){var b=a?w():{x:0,y:0};c(" Reposition requested from iFrame (offset x:"+b.x+" y:"+b.y+")"),v={x:Number(B.width)+b.x,y:Number(B.height)+b.y},f()}function z(){switch(B.type){case"close":d(B.iframe),y.resizedCallback(B);break;case"message":o();break;case"scrollTo":x(!1);break;case"scrollToOffset":x(!0);break;case"reset":g(B);break;case"init":b(),y.initCallback(B.iframe);break;default:b()}}var A=a.data,B={};m()&&(c(" Received: "+A),B=j(),!n()&&q()&&l()&&(z(),p=!1))}function e(){null===v&&(v={x:void 0!==window.pageXOffset?window.pageXOffset:document.documentElement.scrollLeft,y:void 0!==window.pageYOffset?window.pageYOffset:document.documentElement.scrollTop},c(" Get position: "+v.x+","+v.y))}function f(){null!==v&&(window.scrollTo(v.x,v.y),c(" Set position: "+v.x+","+v.y),v=null)}function g(a){function b(){h(a),j("reset","reset",a.iframe)}c(" Size reset requested by "+("init"===a.type?"host page":"iFrame")),e(),i(b,a,"init")}function h(a){function b(b){a.iframe.style[b]=a[b]+"px",c(" IFrame ("+a.iframe.id+") "+b+" set to "+a[b]+"px")}y.sizeHeight&&b("height"),y.sizeWidth&&b("width")}function i(a,b,d){d!==b.type&&w?(c(" Requesting animation frame"),w(a)):a()}function j(a,b,d){c("["+a+"] Sending msg to iframe ("+b+")"),d.contentWindow.postMessage(s+b,"*")}function k(){function b(){function a(a){1/0!==y[a]&&0!==y[a]&&(k.style[a]=y[a]+"px",c(" Set "+a+" = "+y[a]+"px"))}a("maxHeight"),a("minHeight"),a("maxWidth"),a("minWidth")}function d(a){return""===a&&(k.id=a="iFrameResizer"+o++,c(" Added missing iframe ID: "+a+" ("+k.src+")")),a}function e(){c(" IFrame scrolling "+(y.scrolling?"enabled":"disabled")+" for "+l),k.style.overflow=!1===y.scrolling?"hidden":"auto",k.scrolling=!1===y.scrolling?"no":"yes"}function f(){("number"==typeof y.bodyMargin||"0"===y.bodyMargin)&&(y.bodyMarginV1=y.bodyMargin,y.bodyMargin=""+y.bodyMargin+"px")}function h(){return l+":"+y.bodyMarginV1+":"+y.sizeWidth+":"+y.log+":"+y.interval+":"+y.enablePublicMethods+":"+y.autoResize+":"+y.bodyMargin+":"+y.heightCalculationMethod+":"+y.bodyBackground+":"+y.bodyPadding+":"+y.tolerance}function i(b){a(k,"load",function(){var a=p;j("iFrame.onload",b,k),!a&&y.heightCalculationMethod in x&&g({iframe:k,height:0,width:0,type:"init"})}),j("init",b,k)}var k=this,l=d(k.id);e(),b(),f(),i(h())}function l(a){if("object"!=typeof a)throw new TypeError("Options is not an object.")}function m(){function a(a){if("IFRAME"!==a.tagName.toUpperCase())throw new TypeError("Expected <IFRAME> tag, found <"+a.tagName+">.");k.call(a)}function b(a){a=a||{},l(a);for(var b in z)z.hasOwnProperty(b)&&(y[b]=a.hasOwnProperty(b)?a[b]:z[b])}return function(c,d){b(c),Array.prototype.forEach.call(document.querySelectorAll(d||"iframe"),a)}}function n(a){a.fn.iFrameResize=function(b){return b=b||{},l(b),y=a.extend({},z,b),this.filter("iframe").each(k).end()}}var o=0,p=!0,q="message",r=q.length,s="[iFrameSizer]",t=s.length,u="",v=null,w=window.requestAnimationFrame,x={max:1,scroll:1,bodyScroll:1,documentElementScroll:1},y={},z={autoResize:!0,bodyBackground:null,bodyMargin:null,bodyMarginV1:8,bodyPadding:null,checkOrigin:!0,enablePublicMethods:!1,heightCalculationMethod:"offset",interval:32,log:!1,maxHeight:1/0,maxWidth:1/0,minHeight:0,minWidth:0,scrolling:!1,sizeHeight:!0,sizeWidth:!1,tolerance:0,closedCallback:function(){},initCallback:function(){},messageCallback:function(){},resizedCallback:function(){}};b(),a(window,"message",d),window.jQuery&&n(jQuery),"function"==typeof define&&define.amd?define([],m):"object"==typeof exports?module.exports=m():window.iFrameResize=m()}();
//# sourceMappingURL=iframeResizer.map

$(function() {
  var $iFrame = $('#copayCard');
  // For full API see https://github.com/davidjbradshaw/iframe-resizer
  $iFrame.iFrameResize({
    log: true,
    checkOrigin: true, // allow cross-site scripting
    sizeHeight: true,
    sizeWidth: false,
    autoResize: true,
    //enablePublicMethods: true,
  //  heightCalculationMethod: 'bodyScroll'
  });
});

Thursday, 15 October 2015

How to create load more posts in wordpress using jQuery Ajax

Step 1: Put the following javascript in the section.
<script type="text/javascript">
jQuery(document).ready(function($) {
  var page = 1; // What page we are on.
  var ppp = 3; // Post per page
                var posts = 3;
                var author_posts = parseInt(<?php echo get_the_author_posts(); ?> ); // Get all posts
              $("#load_more_posts").click(function() {
               if ((author_posts - posts ) < 0) {
                    $("#load_more_posts").attr('disabled');
                    $("#load_more_posts").css({'cursor': 'default','opacity': '0.61'});
                    $("#load_more_posts").text('No more posts!');
                }else {
                    OffSet = (page * ppp);
                    $.ajax({
                    type: "GET",
                    url: "/WordPress/wp-admin/admin-ajax.php",
                    dataType: 'html',
                    data: ({ action: 'loadMore', offset:OffSet , ppp: ppp}),
                    success: function(data){    
                    //$('#load_posts').append( $.parseHTML(data));
                    var $items = $($.parseHTML(data));
                    $('#load_posts').append( $items ).isotope( 'appended', $items );
                    // #load_posts is the id of main posts container
                    posts = posts + 3;
                    page++;
                    if ((author_posts - posts ) < 0) {
                        $("#load_more_posts").attr('disabled');
                        $("#load_more_posts").css({'cursor': 'default','opacity': '0.61'});
                        $("#load_more_posts").text('No more posts!');
                        }
                    }
                });
            }
        });
    });
 </script>
Step 2: After that put the following code in function.php file.
<?php
 function loadMore() {
        $offset     = $_GET["offset"];
        $ppp         = $_GET["ppp"];
        $args2         = array( 'posts_per_page' => $ppp, 'offset' => $offset, 'orderby' => 'DESC');
        $custom2     = new WP_Query($args2);
        // the Loop
        while ($custom2->have_posts()) : $custom2->the_post();  ?>
        <div class="item">
        <div class="grid-text">   
        <?php the_content('Read More...');?>
        </div>
        </div>
        <?php
        endwhile;
        // Reset Query
        wp_reset_query();
      
}
add_action('wp_ajax_loadMore', 'loadMore');
add_action('wp_ajax_nopriv_loadMore', 'loadMore'); // not really needed
?>
Step 3: Finally put the following code line in index.php page after closing main div of posts container.
<div id="load_more_posts"> Load More</div>

Thursday, 14 May 2015

how to Install SugarCRM on localhost in windows - Step by Step Guide

 I had followed this link when I was installing SugarCRM on my local Server. This link provides step by step solutions for installing SugarCRM on localhost.

http://marwahjatin.blogspot.in/2010/06/install-sugarcrm-step-by-step-guide.html

Thursday, 5 February 2015

How to Upload File in PHP using jquery with multiple file selection, drag&drop support, progress bars, validation and preview images

File Upload widget with multiple file selection, drag&drop support, progress bars, validation and preview images, audio and video for jQuery.
Supports cross-domain, chunked and resumable file uploads and client-side image resizing.
Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.
Please visit the following to download source code.

https://blueimp.github.io/jQuery-File-Upload/

Thursday, 29 January 2015

Tutorial on install, setup and getting started in Symfony 2 PHP MVC framework with Hello World example on Windows


PHP is one of the widely used web development language, and Symfony is an Enterprise level PHP MVC framework. Here the following link is explaining the steps for getting started with Symfony in Windows with a 'Hello World' example in Symfony.

http://www.tinywall.info/2014/05/install-setup-getting-started-tutorial-php-symfony-hello-world-example-windows.html

Friday, 9 January 2015

How to Display Comments on Home Page of a WordPress Site

 I have just put $withcomments = "1"; before comments_template() function.
<?php  
$withcomments = "1"; 
comments_template(); 
 ?>