How To Exclude Posts and Pages in WordPress Search

Sometimes we don’t want to display every page and post in search results. Today I like to explain you how to add filter to the search. For this I have added a filter to the search query of WordPress and exclude posts or pages as per my requirement of the search result.

We can exclude posts and pages by their ID, which we will give to an array and so exclude several posts and pages.

In my first code example the ID’s are set in the array. The filter is only working if it is the search is_search and if you are not ! in the backend is_admin.

// search filter
function my_search_filter($query) {

    if ( !$query->is_admin && $query->is_search) {
        $query->set('post__not_in', array(21, 39) ); // id of page or post
    }

    return $query;
}
add_filter( 'pre_get_posts', 'my_search_filter' );

If you like to exclude the subpage of any page, then you can add below code.

// search filter
function my_search_filter($query) {

    if ( !$query->is_admin && $query->is_search) {
        $pages = array(21, 39); // id of page or post
        // find children to id
        foreach( $pages as $page ):
            $childrens = get_pages( array('child_of' => $page, 'echo' => 0) );
        endforeach;
        // add id to array
        for($i = 0; $i < sizeof($childrens); ++$i) {
            $pages[] = $childrens[$i]->ID;
        }
        $query->set('post__not_in', $pages );
    }

    return $query;
}
add_filter( 'pre_get_posts', 'my_search_filter' );

There are too many possibilities to do this but I think this is a useful post for you.

How to Integrate responsive-nav.js into WordPress Navigation

Responsive Web Design is all the rage these days. Clients are asking for it, web developers are expected to know it, and most importantly, mobile devices are more popular than ever. One big area of a website is website navigation. In my post, I talk all about responsive navigation and how to make it work nicely in WordPress.

responsive-nav.js is a fantastic, and more importantly, light-weight, piece of javascript code that will automatically switch out your current, full-width navigation for an animated pull-down section on mobile. In this post, we will:

  1. Define our menu
  2. Enqueue responsive-nav.js and accompanying CSS
  3. Add the javascript that does the heavy lifting to our template

So let’s start with the easy part: defining new menu. In functions.php of current theme:

<?php 
if ( function_exists( 'add_theme_support' ) ) { 
    add_theme_support( 'menus' );
}
?>

Then add this to your header.php (or wherever you want to add the menu):

<nav class="nav-menu">
    <?php wp_nav_menu( array('menu' => 'Main' )); ?>
</nav>

Perfect! Now you can choose the “Main” menu from the WordPress Menu admin section. Next, Enqueue responsive-nav.js. Now head over to responsive-nav.com and download the files. I always place theme-specific javascript and it’s CSS in a folder called /js/ in the theme folder.

Now, Again open up functions.php and add this:

<?php 
function responsive_scripts() {
    wp_enqueue_script('responsive-nav', get_template_directory_uri() .'/js/responsive-nav.js');
    wp_enqueue_style('resnav-css', get_template_directory_uri() .'/css/responsive-nav.css');
}
add_action( 'wp_enqueue_scripts', 'responsive_scripts' );

function responsive_footer_script(){
 echo '<script>
           var navigation = responsiveNav(".nav-menu", {
               label: "- navigate -"
           });
       </script>';
}
add_action( 'wp_footer', 'responsive_footer_script' );
?>

The above code will properly add the script & CSS to the of your theme.

That’s it! Now you have a responsive nav menu in your website.

Taking Control of WordPress 3.8 Admin Bar

What is WordPress Admin Bar?

WordPress admin bar was introduced in WordPress 3.1. The purpose of the WordPress Admin Bar was to connect the backend (dashboard) of a WordPress to the Live. It always shows up right below the browser address bar and looks somewhat like below image:

wordpress admin nav

The WordPress Admin Bar helps webmasters switch to the basic features of the Dashboard directly from their WordPress front-end. Although the presence of the WordPress Admin Bar is a boon, most webmasters don’t like the presence of anything sitting on our sites, I guess the 1-click access to the WordPress Dashboard isn’t what everybody is comfortable with.

Why an Admin Bar?

“First step towards a front-end editor” – Matt Mullenweg, the man who gave birth to WordPress.

The WordPress admin bar has been tagged as the first step towards bringing the WordPress editor right into your site and moving it out of the Dashboard. It will be interesting to see how WordPress incorporates the Dashboard features into our blog’s front end without making it tacky. For now, Admin Bar is here and needs a lot of improvements.

Remove Links from the WordPress Admin Bar

There is lot of things, That you want to remove from the WordPress Admin Bar. Before we start with adding new links to the WordPress Admin Bar (which is a bit complex) we will start removing remove links from the WordPress Admin Bar.

Remove Author Name Menu or just sub-parts

The very first drop down menu in the WordPress Admin Bar is the name of author. It will have two options – Edit Profile and Logout. You can remove this complete menu (or just the sub-parts) by inserting the below code in

functions.php

of your current theme:

<?php

function editMyAdminBar() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_menu('my-account-with-avatar');
    // This will hide the menu item with author name.

    $wp_admin_bar->remove_menu('edit-profile');
    // This will remove the sub-part "Edit My Profile".

    $wp_admin_bar->remove_menu('logout');
    // This will remove the sub-part "Logout".
}

add_action('wp_before_admin_bar_render', 'editMyAdminBar');
?>

Next is the Dashboard link in the WordPress Admin Bar. Insert below code in

functions.php

:

<?php

function editMyAdminBar() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_menu('dashboard');
}

add_action('wp_before_admin_bar_render', 'editMyAdminBar');
?>

Next is the Add New link which has lot of sub items too and we have some other menus in our admin bar. Use the below code to remove all or sub items:

<?php

function editMyAdminBar() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_menu('new-content');
    // This removes the complete menu “Add New”. You will not require the below “remove_menu” if you using this line.

    $wp_admin_bar->remove_menu('new-post');
    // This will hide the menu item “Post”.

    $wp_admin_bar->remove_menu('new-page');
    // This will hide the menu item “Page”.

    $wp_admin_bar->remove_menu('new-media');
    // This will hide the menu item “Media”.

    $wp_admin_bar->remove_menu('new-link');
    // This will hide the menu item “Link”.

    $wp_admin_bar->remove_menu('new-user');
    // This will hide the menu item “User”.

    $wp_admin_bar->remove_menu('new-theme');
    // This will hide the menu item “Theme”.

    $wp_admin_bar->remove_menu('new-plugin');
    // This will hide the menu item “Plugin”.

    $wp_admin_bar->remove_menu('comments');
    // This will hide the menu “Comments”.

    $wp_admin_bar->remove_menu('appearance');
    // This removes the complete menu “Appearance”. You will not require the below “remove_menu” if you using this line.

    $wp_admin_bar->remove_menu('new-themes');
    // This will hide the menu item “Themes”.

    $wp_admin_bar->remove_menu('new-widgets');
    // This will hide the menu item “Widgets”.

    $wp_admin_bar->remove_menu('new-menus');
    // This will hide the menu item “Menus”.

    $wp_admin_bar->remove_menu('updates');
    // This will hide the menu “Updates”.

    $wp_admin_bar->remove_menu('get-shortlink');
    // This will hide the menu “Shortlink”.
}

add_action('wp_before_admin_bar_render', 'editMyAdminBar');
?>

Now we are moving to Add Links to WordPress Admin Bar

Most of sites have a link to the homepage, if you want to add one then you can use the below code in your

functions.php

:

<?php
function add_new_item_to_adminbar() {
    global $wp_admin_bar;
    $wp_admin_bar->add_menu(array(
        'id' => 'view-site', //the view-site ID that refers to what we are doing.
        'title' => __('Visit Site'), //the anchor text that links to homepage.
        'href' => site_url())); //the homepage URL to which the anchor text will connect.
}

add_action('wp_before_admin_bar_render', 'add_new_item_to_adminbar');
?>

Add sub-menu item in “Add New” menu

This will be interesting. We will add a new item inside a menu that already exists. The below code will add a My Media option in the menu Add New.

<?php
function add_submenu_to_adminbar() {
    global $wp_admin_bar;
    $wp_admin_bar->add_menu( array(
        'parent' => 'new-content',
        // new-content is the ID for “Add New” menu so we use it as parent ID.
        
        'id' => 'new_media', 
        // You can add any value here as you are adding something very new here.
        
        'title' => __('Media'), // The anchor text.
        
        'href' => admin_url( 'media-new.php') 
        // name of file to which you will link to.
        ));
}
add_action( 'wp_before_admin_bar_render', 'add_submenu_to_adminbar' );
?>

Hope! this is a good tutorial for all my blog reader, If any one have any query’s and error please put your comments bellow.

Notify WordPress users of newly published post

So you have a post section and each time you publish a new custom post you’d like to notify all your users (subscriber). It could be a post, a product, an event or perhaps a tutorial etc.

Usually the action hook would be ‘publish_post’ or ‘publish_page’ but those hooks only work for Posts and Pages.

The following example shows how this can be done to notify users that a Deputy Head has submitted a lesson for review:

<?php
function notify_users($post_ID)  {
	// a conditional to check that this is a new post
	if( ( $_POST['post_status'] == 'publish' ) && ( $_POST['original_post_status'] != 'publish' ) ) {
		// get all users email addresses
		$wp_user_search = new WP_User_Query( array( 'fields' => array('user_email') ) );
		$usersarray = $wp_user_search->get_results();
		$arrUsers = array();
		// store each email for later use
		for ($arr = $usersarray, $allU = count($arr), $key = 0; $key < $allU; $key++) {
			$arrUsers[] = $arr[$key]->user_email;
		}
		// create the from details 
		$headers[] = 'From: Site Admin<admin@example.net>';
		// lets cc in the head just because we can 
		$headers[] = 'Cc: Site Support <support@example.net>';
		// separate the users array
		$users = implode(",", $arrUsers);
		// concatenate a message together
		$message = 'A new post has been opened for your review on the site ' . get_bloginfo('siteurl') . "\r\n\r\n";
		$message .= 'You can review it now at ' . get_permalink($post_ID) . "\r\n\r\n";
		$message .= 'Feel free to leave a comment and any suggestions.' . "\r\n\r\n";
		$message .= 'Praveen Shekhawat.';
		// and finally send the email
		wp_mail($users, "Blog Title: "  . $_POST['post_title'] , $message, $headers );
	    return $post_ID;
    }
}
// hook on to the custom post type by using 'publish_lesson'
add_action('publish_post', 'notify_users');
?>

These hooks will not work with custom post types! So, what about custom post types?

Please use bellow hook for custom post types.

<?php
/* a custom post type called ‘event’ you can now use ‘publish_event’ to hook your function */
add_action('publish_event', 'notify_users');
?>

It’s really is as simple as that.

How to create a new WordPress array ?

So you have a set of data stored in an array and you want to put aside or create a new array with certain data.

There is a powerful function called wp_list_pluck() and wp_list_filter() that can be used for such tasks with any sort of datasets.

For example consider the following array:

$allUsers = array(
    array(
        'id' => 1,
        'user_name' => 'praveen',
        'email' => 'ravan@example.com',
        'type' => 'admin',
        'status' => 'active',
    ),
    array(
        'id' => 2,
        'user_name' => 'dinesh_silwani',
        'email' => 'silwani@example.com',
        'type' => 'guest',
        'status' => 'disabled',
    ),
    array(
        'id' => 3,
        'user_name' => 'ronak',
        'email' => 'ronak@example.com',
        'type' => 'host',
        'status' => 'disabled',
    ),
    array(
        'id' => 4,
        'user_name' => 'ravi',
        'email' => 'ravi@example.com',
        'type' => 'guest',
        'status' => 'disabled',
    ),
    array(
        'id' => 5,
        'user_name' => 'gopal',
        'email' => 'gopal@example.com',
        'type' => 'host',
        'status' => 'active',
    ),
);

First of all we are going to use wp_list_pluck() with 2 parameters, the array to pluck and the key to be plucked. So to create another array that contains just the key for the “user_name” we would do the following:

$allUserName = wp_list_pluck($allUsers, 'user_name'); // New array with all user names.
// would produce the following
// array('praveen', 'dinesh_silwani', 'ronak', 'ravi', 'gopal');

The same could be done to collate the id’s for later loops:

$allIDs = wp_list_pluck($allUsers, 'id');
// would produce the following
// array('1', '2', '3', '4', '5');

Now we are moving to another function. wp_list_filter() is another useful and powerful function that can be used to further refine your new array, say for instance you’d like to create a new array with just guest that are disabled, this is how you can go about it:

$filter_to_use = array('type' => 'guest', 'status' => 'disabled');
$allGuest = wp_list_filter($allUsers, $filter_to_use); // $allUsers = "all disabled guest user."
// this would end up creating an array like so
// array(
//    array(
//        'id' => 2,
//        'user_name' => 'dinesh_silwani',
//        'email' => 'silwani@example.com',
//        'type' => 'guest',
//        'status' => 'disabled',
//    ),
//    array(
//        'id' => 4,
//        'user_name' => 'ravi',
//        'email' => 'ravi@example.com',
//        'type' => 'guest',
//        'status' => 'disabled',
//    )
//);

Both of these functions are very useful when is comes to creating new arrays.

How to use PayPal standrad with reccuring method.

Use this bellow html form into your code :

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">

<!-- Identify your business so that you can collect the payments. -->

<input type="hidden" name="business" value="example@example.com">

<!-- Specify a Subscribe button. -->

<input type="hidden" name="cmd" value="_xclick-subscriptions">

<!-- Identify the subscription. -->

<input type="hidden" name="item_name" value="Alice's Weekly Digest">
<input type="hidden" name="item_number" value="DIG Weekly">

<!-- Set the terms of the 1st trial period. -->

<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="a1" value="0">
<input type="hidden" name="p1" value="7">
<input type="hidden" name="t1" value="D">

<!-- Set the terms of the 2nd trial period. -->

<input type="hidden" name="a2" value="5.00">
<input type="hidden" name="p2" value="3">
<input type="hidden" name="t2" value="W">

<!-- Set the terms of the regular subscription. -->

<input type="hidden" name="a3" value="49.99">
<input type="hidden" name="p3" value="1">
<input type="hidden" name="t3" value="Y">
<input type="hidden" name="src" value="1">

<!-- Display the payment button. -->
<input type="image" name="submit" border="0" src="https://www.paypal.com/en_US/i/btn/btn_subscribe_LG.gif" alt="PayPal - The safer, easier way to pay online" />

<img alt="" border="0" width="1" height="1" src="https://www.paypal.com/en_US/i/scr/pixel.gif" >

</form>
Name Required or Optional Description Character Length
business Required Your PayPal ID or an email address associated with your PayPal account. Email addresses must be confirmed.
item_name Optional Description of item being sold (maximum 127 characters). If you are collecting aggregate payments, this can include a summary of all items purchased, tracking numbers, or generic terms such as “subscription.” If omitted, customer will see a field in which they have the option of entering an Item Name
currency_code Optional The currency of prices for trial periods and the subscription. The default isUSD. 3
a1 Optional Trial period 1 price. For a free trial period, specify0.
p1 See description. Trial period 1 duration. Required if you specifya1. Specify an integer value in the allowable range for the units of duration that you specify witht1. 2
t1 See description. Trial period 1 units of duration. Required if you specifya1. Allowable values:

  • D– for days; allowable range for p1 is 1 to 90
  • W– for weeks; allowable range for p1 is1 to52
  • M– for months; allowable range for p1 is1 to24
  • Y– for years; allowable range forp1 is1 to 5
1
a2 Optional Trial period 2 price. Can be specified only if you also specify a1.
p2 See description. Trial period 2 duration. Required if you specify a2. Specify an integer value in the allowable range for the units of duration that you specify with t2. 2
t2 See description. Trial period 2 units of duration. Allowable values:

  • D– for days; allowable range for p1 is 1 to 90
  • W– for weeks; allowable range for p1 is1 to52
  • M– for months; allowable range for p1 is1 to24
  • Y– for years; allowable range forp1 is1 to 5
1
a3 Required Regular subscription price.
p3 Required Subscription duration. Specify an integer value in the allowable range for the units of duration that you specify with t3. 2
t3 Required Regular subscription units of duration. Allowable values:

  • D– for days; allowable range for p1 is 1 to 90
  • W– for weeks; allowable range for p1 is1 to52
  • M– for months; allowable range for p1 is1 to24
  • Y– for years; allowable range forp1 is1 to 5
1
src Optional Recurring payments. Subscription payments recur unless subscribers cancel their subscriptions before the end of the current billing cycle or you limit the number of times that payments recur with the value that you specify for srt.Allowable values:

  • 0 – subscription payments do not recur
  • 1 – subscription payments recur

The default is 0.

1
srt Optional Recurring times. Number of times that subscription payments recur. Specify an integer above 1. Valid only if you specify src=”1″. 1
sra Optional Reattempt on failure. If a recurring payment fails, PayPal attempts to collect the payment two more times before canceling the subscription.Allowable values:

  • 0 – do not reattempt failed recurring payments
  • 1 – reattempt failed recurring payments before canceling

The default is 1.

For more information, see

1
no_note Required Do not prompt payers to include a note with their payments. Allowable values for Subscribe buttons:

  • 1 – hide the text box and the prompt For Subscribe buttons, always include no_noteand set it to 1.
1
custom Optional User-defined field which will be passed through the system and returned in your merchant payment notification email. This field will not be shown to your subscribers. 255
invoice Optional User-defined field which must be unique with each subscription. The invoice number will be shown to subscribers with the other details of their transactions 127
modify Optional Modification behavior. Allowable values:

  • 0– allows subscribers to only create new subscriptions
  • 1– allows subscribers to modify their current subscriptions or sign up for new ones
  • 2– allows subscribers to only modify their current subscriptions. The default value is 0.
1
usr_manage Optional Set to1to have PayPal generate usernames and initial passwords for subscribers. 1

How to integrate DIBS payment gateway api in php ?

Integrating DIBS payment Gateway(Redirect method and API method)

 

HTML Form
Redirect method

  • Integrating DIBS payment Gateway is Simple ,You need to create a test account in dibs and with those details we can integrate dibs in your application
  • Integrating via redirect method or server post method
  • After the saving the buy details just save those in your Database and after that redirect to the below form page with filled details and need to submit
  • Below is the example of sample dibs form
<form action="https://pay.dibspayment.com/" method="post" name="dibs">
    <input type="hidden" name="merchant" value="merchant_id" />
    <input type="hidden" name="account" value="account-name" />
    <input type="hidden" name="amount" value="TotalPrice*100" />
    <input type="hidden" name="currency" value="208" />
    <input type="hidden" name="orderid" value="unique_id" />
    <input type="hidden" name="acceptReturnUrl" value="http://www.yoururl.com/success.php" />
    <input type="hidden" name="paytype" value="cardtype" />
    <input type="hidden" name="uniqueid" value="uniqueid" />
    <input type="hidden" name="callbackurl" value="http://www.yoururl.com/callbackurl.php"/>
    <input type="hidden" name="cancelreturnurl" value="http://www.yoururl.com/error.php" />
    <input type="hidden" name="language" value="da_DK" />
    <input type="hidden" name="test" value="1" />
</form>

After the Successfull Payment user will be redirected to our website(accepturl)

<?php
$Merchant = "123456";
$MD5 = "qJuH6vjXHLSDB*%€&/hbnkjlBHGhjJKJ";
$test ="yes";
if($_GET['status']=='ACCEPTED'){
$paid = DIBSCapt($Merchant,$_GET['amount'], $_GET['transaction'],$_GET['orderid'],$MD5,$test);
if ($paid==true){ /* Payment Captured */ }else{ /* Payment Failed */ }
}
?> 

API Method

  • For API or webservice Way of Payment Integration
  • Just need to call two functions for capturing the Payment
  • First need to authorise the Payment by calling
 <?php
$trancaction = DIBSAuth($Merchant,$Amount,$Currency,$CardNo, $ExpMon,$ExpYear,$CVC,$OrderID,$postype="ssl", $MD5="",$test="no");
$paid = DIBSCapt($Merchant,$amount,$trancaction['transaction'], $trancaction['orderid'],$MD5,$test);
if ($paid==true){ /* Payment Captured */ }else{ /* Payment Failed */ }
?>

CODE Include this functions

 <?php //!A function for asking DIBS for authorisation of a creditcard payment
function DIBSAuth($Merchant,$Amount,$Currency,$CardNo,$ExpMon, $ExpYear,$CVC,$OrderID,$postype="ssl",$MD5="",$test="no") {

//Set up post-variable string
$postvars = "merchant=".parmchk($Merchant);
$postvars .= "&orderid=".parmchk($OrderID);
$postvars .= "&currency=".parmchk($Currency);
$postvars .= "&amount=".parmchk($Amount);

//Check if MD5key check is used and add if it is

if ( count($MD5) == 2 ) {
$md5Key = md5($MD5['K2'].md5($MD5['K1'].$postvars));
$postvars .= "&md5key=".$md5Key;
}

$postvars .= "&cardno=".parmchk($CardNo);
$postvars .= "&expmon=".parmchk($ExpMon);
$postvars .= "&expyear=".parmchk($ExpYear);
$postvars .= "&cvc=".parmchk($CVC);
$postvars .= "&textreply=yes";
$postvars .= "&postype=".parmchk($postype);


//Add testvar if "yes"

if ( $test == "yes" ) {
$postvars .= "&test=yes";
}

//Send post request
$response = http_post(‘payment.architrade.com’,'/cgi-ssl/auth.cgi’, $postvars );

//Deal with reponse
$response = explode("&",$response);
$N = count($response);
if ( $N < 2 ) { 
//Response is an error
$AuthInfo = false;
} 
else { 
//Response is good (does not mean that authorisation was granted)
$AuthInfo = array(); //Define output array
while ( $N– > 0 ) {
$A = explode("=",$response[$N]);
$AuthInfo[$A[0]] = $A[1];
}
}

//Check that the returned MD5 key is correct
if ( $AuthInfo['authkey'] != "" ) {
$vars = "transact=".$AuthInfo['transact']."&amount=".$Amount."&currency=".$Currency;
$Control = md5($MD5['K2'].md5($MD5['K1'].$vars));
if ( $Control != $AuthInfo['authkey'] ) {
$AuthInfo = array();
$AuthInfo['result'] = "MD5key authorisation failed";
}
}

return $AuthInfo;
}

//!A function for asking DIBS for capturing an already authorised creditcard payment
function DIBSCapt($Merchant,$Amount,$Transact,$OrderID,$MD5,$test="no") {

//Set up post-variable string
$postvars = "merchant=".parmchk($Merchant);
$postvars .= "&orderid=".parmchk($OrderID);
$postvars .= "&transact=".parmchk($Transact);
$postvars .= "&amount=".parmchk($Amount);

//Check if MD5key check is used and add if it is
if ( count($MD5) == 2 ) {
$md5Key = md5($MD5['K2'].md5($MD5['K1'].$postvars));
$postvars .= "&md5key=".$md5Key;
}

$postvars .= "&textreply=yes";
$postvars .= "&force=true";

//Add testvar if "yes"
if ( $test == "yes" ) {
$postvars .= "&test=yes";
}

//Send post request
$response = http_post(‘payment.architrade.com’,'/cgi-bin/capture.cgi’, $postvars );

//Deal with reponse
$response = explode("&",$response);
$N = count($response);
if ( $N == 1 ) {
$CaptInfo['result'] = $response[0];
} else {
if ( $N < 2 ) { 
//Response is an error
$CaptInfo = false;
} 
else { 
//Response is good (does not mean that the capture was successfull)
$CaptInfo = array(); //Define output array
while ( $N– > 0 ) {
$A = explode("=",$response[$N]);
$CaptInfo[$A[0]] = $A[1];
}
}
}

return $CaptInfo;
}

//!Function for sending a ‘within-php’ post-request and receive the response-body as a string
function http_post($host, $path, $data, $auth="") {

$sock = fsockopen("ssl://".$host, 443, $errno, $errstr, 30);
if (!$sock) die("$errstr ($errno)\n");

fwrite($sock, "POST ".$path." HTTP/1.0\r\n");
fwrite($sock, "Host: ".$host."\r\n");
fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
fwrite($sock, "User-Agent: PHP-DIBS (Kaka Consult) v1.0 \r\n");

//If basic authentication is required (e.g. payinfo.cgi, changestatus.cgi and refund.cgi)
if ( is_array($auth) ) {
fwrite($sock, "Authorization: Basic ".base64_encode($auth['username'].":".$auth['password'])."\r\n");
}

fwrite($sock, "Accept: */*\r\n");
fwrite($sock, "\r\n");
fwrite($sock, $data."\r\n");
fwrite($sock, "\r\n");

//Take out the header first
$headers = "";
while ( $str = trim(fgets($sock, 4096)) ) {
$headers .= "$str\n";
}

//Then collect the body and prepare for returning
$body = "";
while ( !feof($sock) ) {
$body .= fgets($sock, 4096);
}

fclose($sock);

return $body;
}

//!Function for checking that the parameters do not contain any &, which may corrupt message to DIBS
function parmchk($in) {
return str_replace("&","",$in);
}
?> 

Paginate WordPress posts with a thumbnail image

Its always nice to give your website users the ability to paginate through your posts, and there are a couple of simple inbuilt functions that will allow you to do so from with in the individual posts, by that I mean these functions should be used on the single.php template or single-{post-type}.php template.

By using get_previous_post() and get_next_post() you can retrieve all the information you need from the previous. If you want to find out more go checkout the codex in the links provided for both functions.

Using the following you can output the link to the previous post of the currently viewed post:

<?php
/*
 * get_previous_post() will return previous post full details in a object.
 * get_permalink() will return permalink of given post ID.
 */
$previous = get_previous_post();
echo get_permalink($previous->ID);
?>

using the get_next_post() you can do the same to get the opposite or get the next post of the currently viewed post like so:

<?php
/*
 * get_next_post() will return next post full details in a object.
 * get_permalink() will return permalink of given post ID.
 */
$next = get_next_post();
echo get_permalink($next->ID);
?>

Now that you can access the ID of the previous and next post we can use another function to get the thumbnail of those posts using the get_the_post_thumbnail() function like this:

<?php
/* get_the_post_thumbnail() will return post thumbnail */
echo get_the_post_thumbnail($previous->ID, 'thumbnail');
?>
<!-- or -->
<?php
/* get_the_post_thumbnail() will return post thumbnail */
echo get_the_post_thumbnail($next->ID, 'thumbnail');
?>

All you need to do now is to wrap the code up in your mark up to make it your own, putting it all together it might look something like this:

<?php
    $previous = get_previous_post();
    $next = get_next_post();
?>
<div class="paginateDiv">
    <div class="previous">
        <a title="<?php echo esc_attr($previous->post_title); ?>" href="<?php echo get_permalink($previous->ID); ?>">
            <?php echo get_the_post_thumbnail($previous->ID, 'thumbnail'); ?>
        </a>
    </div>
    <div class="next">
        <a title="<?php echo esc_attr($next->post_title); ?>" href="<?php echo get_permalink($next->ID); ?>">
            <?php echo get_the_post_thumbnail($next->ID, 'thumbnail'); ?>
        </a>
    </div>
</div>

Your html markup and css should be modified for your own designs but as long as you are on the single.php template then your users will now be able to paginate WordPress posts with a thumbnail image of the previous and next posts.

How to get thumbnail of YouTube video link using YouTube API?

Each YouTube video has 4 generated images. They are predictably formatted as follows:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg

The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (ie. one of 1.jpg, 2.jpg, 3.jpg) is:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

For the high quality version of the thumbnail use a url similar to this:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

There is also a medium quality version of the thumbnail, using a url similar to the HQ:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

For the maximum resolution version of the thumbnail use a url similar to this:

http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

All of the above urls are available over https too. Just change http to https in any of the above urls.

Alternatively, you can use the YouTube API to get thumbnail images.