Pages

Oct 6, 2016

Prevent DDoS attack in wordpress



By default, this feature is enabled in all Wordpress installs, and isn't quite easy to turn off. Add the following API filter to Wordpress:

add_filter( ‘xmlrpc_methods’, function( $methods ) {

   unset( $methods['pingback.ping'] );   return $methods;} );

Removing xmlrpc.php is not recommended as it will breack a number of other features that will use the API.

Aug 21, 2016

Add a '' container inside after every 3 loops




Add a '<div></div>'  container inside after every 3 loops
As an example

<div>
    title
    title
    title
</div>
<div>
    title
    title
    title
</div>
<div>
    title
    title
    title
</div>
.
.
.
$dummyarray is in format of
$dummyarray = array(


[0] => 'title',

[1] => 'title',

[2] => 'title',

[3] => 'title',

.
.
)

foreach (array_chunk($dummyarray, 3, true) as $array)
{
    echo '<div>';
    foreach($array as $foo)
    {
         echo $foo->title;
    }
    echo '</div>';
}

Jun 20, 2016

Create CRON In wordpress with custom interval


Create CRON In wordpress with custom interval


// add custom interval
function cron_add_minute( $schedules ) {
// Adds once every minute to the existing schedules.
    $schedules['everyminute'] = array(
   'interval' => 60,
   'display' => __( 'Once Every Minute' )
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'cron_add_minute' );



add_action('recheck_event', 'recheck_verification');

function schedule_event() {
if ( !wp_next_scheduled( 'recheck_event' ) ) {
wp_schedule_event( current_time( 'timestamp' ), 'everyminute', 'recheck_event');
}
}
add_action('wp', 'schedule_event');

function recheck_verification() {

 //You Custom Function

}

Jun 18, 2016

Prevent admin notification email for new registered users or user password changes

This is a simple method to prevent any mails to admin which normaly takes place on new user registration or user changes there password. Put this function on your Function.php file any where.

// prevent admin notification email for new registered users or user password changes



function conditional_mail_stop() {

    global $phpmailer;

    $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
    $subject = array(
        sprintf(__('[%s] New User Registration'), $blogname),
        sprintf(__('[%s] Password Lost/Changed'), $blogname)
    );

    if ( in_array( $phpmailer->Subject, $subject ) )
        // empty $phpmailer class -> email cannot be send
        $phpmailer = new PHPMailer( true );

}

add_action( 'phpmailer_init', 'conditional_mail_stop' );

May 27, 2016

FUNCTION TO ADD CUSTOM STYLE SHEET IN A PLUGIN

FUNCTION TO ADD CUSTOM STYLE SHEET IN A PLUGIN


function msg_script_init() {

 wp_enqueue_style("msgcs", plugins_url('user-messages/css/msgcss.css'), false, "0.0", "all");

}
add_action('admin_init', 'msg_script_init');

May 3, 2016

How to add custom Google Translation with custom flag

Adding google translation to any page in html/php using Google Translation


Create span element for flags :-

  <span class="flags">
                   <span class="flag_click eng" data-val = 'en'><flag-img></span>
                   <span class="flag_click spn" data-val = 'es'><flag-img></span>
 

 

 

 


Add following Script below this :-

 

 

 

<script>
               
 function changeLang(someth) {
    var nLang = someth;//someth.value,
        evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    jQuery('.goog-te-combo').val(nLang)[0].dispatchEvent(evt);
}

   jQuery('document').ready(function () {
                 jQuery('.flag_click').click(function () {
                    
                 var va =  jQuery(this).attr('data-val');
                  changeLang(va);
                   });
     });
    </script>
   
<div class="translator_div" style="display:none;"> 

                            <div id="google_translate_element"></div><script type="text/javascript">
                            function googleTranslateElementInit() {
                            new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'en,es', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element');
                            }
                            </script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
   </div>

 

 

Apr 22, 2016

Using Jquery hiw To get values In A Text Box On “Keyup” Event


How to Get Values In A Text Box On “Keyup” Event using jquery


<input type=”text” id=”keywords” value=””/>
<script>
jQuery(“#keywords”).keyup(function(e)
{
var searchbox = jQuery(this).val();
alert(searchbox);
});
</script>

Mar 18, 2016

Print Avatar Image For A User In WordPress

Many times we have wondered how to show a simple user image in there profile.Here is a simple method to do that, simple codes to show avatar.


<?php
echo get_avatar( $userid, 25 );
?>
Here 25 is the size of image
it can be 25,50 or custom image size


Mar 4, 2016

WAY TO REMOVE WORDPRESS FAILURE NOTICE ON A SECOND LOGOUT ATTEMPT

WAY TO REMOVE WORDPRESS FAILURE NOTICE ON A SECOND LOGOUT ATTEMPT 

 

function smart_logout() {


if (!is_user_logged_in()) {
$smart_redirect_to = !empty( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '/';
wp_safe_redirect( $smart_redirect_to );
exit();
} else {
check_admin_referer('log-out');
wp_logout();
$smart_redirect_to = !empty( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '/';
wp_safe_redirect( $smart_redirect_to );
exit();
}


}
add_action ( 'login_form_logout' , 'smart_logout' );

 



Feb 28, 2016

Get And Share Visitor's Location using Browser


Fetch your Sites Visitor's Location(Longitude & Lattitiude) using a simple javascript



if (navigator.geolocation) {
       
        navigator.geolocation.getCurrentPosition(function (position) {
          myLatLng = new google.maps.LatLng(position.coords.latitude,                  position.coords.longitude);
   alert(myLatLng )
        },
        function () {
                alert('fallback'); 
        });
     }

Feb 25, 2016

Prevent no page found for Skype call link

function ss_allow_skype_protocol( $protocols ){
$protocols[] = 'skype';
return $protocols;
}
add_filter( 'kses_allowed_protocols' , 'ss_allow_skype_protocol' );
Then add link as  

 <a href="skype:[skype_username]?call">Skype</a>


 in any template

Feb 23, 2016

Buddypress Function Forcing Add Friend

Buddypress Function Forcing Add Friend




simple time Function to display time as facebook styled


function time_passed($timestamp){
//type cast, current time, difference in timestamps
$timestamp = (int) $timestamp;
$current_time = time();
$diff = $current_time – $timestamp;
//intervals in seconds
$intervals = array (
‘year’ => 31556926, ‘month’ => 2629744, ‘week’ => 604800, ‘day’ => 86400, ‘hour’ => 3600, ‘minute’=> 60
);
//now we just find the difference
if ($diff == 0)
{
return ‘just now';
}
if ($diff < 60)
{
return $diff == 1 ? $diff . ‘ second ago’ : $diff . ‘ seconds ago';
}
if ($diff >= 60 && $diff < $intervals[‘hour’])
{
$diff = floor($diff/$intervals[‘minute’]);
return $diff == 1 ? $diff . ‘ minute ago’ : $diff . ‘ minutes ago';
}
if ($diff >= $intervals[‘hour’] && $diff < $intervals[‘day’])
{
$diff = floor($diff/$intervals[‘hour’]);
return $diff == 1 ? $diff . ‘ hour ago’ : $diff . ‘ hours ago';
}
if ($diff >= $intervals[‘day’] && $diff < $intervals[‘week’])
{
$diff = floor($diff/$intervals[‘day’]);
return $diff == 1 ? $diff . ‘ day ago’ : $diff . ‘ days ago';
}
if ($diff >= $intervals[‘week’] && $diff < $intervals[‘month’])
{
$diff = floor($diff/$intervals[‘week’]);
return $diff == 1 ? $diff . ‘ week ago’ : $diff . ‘ weeks ago';
}
if ($diff >= $intervals[‘month’] && $diff < $intervals[‘year’])
{
$diff = floor($diff/$intervals[‘month’]);
return $diff == 1 ? $diff . ‘ month ago’ : $diff . ‘ months ago';
}
if ($diff >= $intervals[‘year’])
{
$diff = floor($diff/$intervals[‘year’]);
return $diff == 1 ? $diff . ‘ year ago’ : $diff . ‘ years ago';
}
}

Feb 21, 2016

Get Geo Coordinates Of An Address

Get Geo Coordinates Of An Address



function getCoordinates($address){

$address = str_replace(” “, “+”, $address); // replace all the white space with “+” sign to match with google search pattern

$url = “http://maps.google.com/maps/api/geocode/json?sensor=false&address=$address”;

$response = file_get_contents($url);

$json = json_decode($response,TRUE); //generate array object from the response from the web

return ($json[‘results’][0][‘geometry’][‘location’]);

}

Feb 19, 2016

WordPress Sample Ajax Function For Any Theme Or Plugin

WordPress sample ajax function for any theme or plugin.
Place this in a template page or any custom page(.php)



<script>
jQuery(‘.click_button’).click(function(){
var id = jQuery(this).attr(‘id’);
var security = ‘<?php echo wp_create_nonce( ‘check-nonce’ ); ?>'; //You can name it anything you like //This is important
jQuery.ajax({
url:”<?php echo admin_url(‘admin-ajax.php’); ?>”,
type:’POST’,
// data:’action=del_image&img_id=’ + img_id,
data:’action=actionhere&id=’+id+’&security=’+security ,
success:function(results)
{
alert(results);//Or any required action
}
});
});
</script>
place this in theme’s/plugins’s function.php

<?php
add_action(‘wp_ajax_actionhere’, ‘actionhere_callback’);
add_action(‘wp_ajax_nopriv_actionhere’, ‘actionhere_callback’);
function actionhere_callback() {
$id = $_POST[‘id’];
$do_check =check_ajax_referer( $security,’check-nonce’,false );
//————————–custom function start————-//
/**************************************************************/
/****** ********/
/****** CUSTOM FUNCTION ********/
/****** ********/
/**************************************************************/
//————————–custom function end————-//
die();//This is important
}
?>

Feb 18, 2016

Get Post Id From POST Permalink/URL

Many  times there is a need to get post id ,and we only gets page or post urls.with this code you can get post id.



We can get Post Id by URLusing wordpress funciton
 
   $post_id  =  url_to_postid( '<post URL /PERMALINK here' );

JavaScript has had the XMLHttpRequest

JavaScript has had the XMLHttpRequest



If you hang out with designers and developers at all, then you’ve probably heard the term “Ajax” by now. It’s the official buzzword of Web 2.0. But it’s also an extremely useful web development technique.
In the course of this tutorial, we’re going to look at what Ajax can do. Then we’ll use a JavaScript class to simplify your first steps toward the ultimate in speedy user interactivity.
First, what is Ajax? It stands for Asynchronous JavaScript And XML. In simple speak, Ajax allows us to use JavaScript to grab an XML file (or any other text) without reloading the whole web page.
Ajax has been used for a lot of things, but it is most impressive when many small updates are needed in a short period. Think streaming stock quotes or draggable maps.
In our example, we’ll use a pair of dropdown menu boxes (SELECT tags in HTML). A selection in the first box affects our list of choices in the second box. It’s not exactly cutting edge (Thau did something similarusing JavaScript), but it’s a proof of concept.

WordPress Last Insert Id,Last Query Executed

WordPress last insert id,last query executed
Get last inserted ID after a query is executed Using this simple scripts:

 

$lastid = $wpdb->insert_id;
$last_query = $wpdb->last_quey;
echo $lastid;
echo $last_query;

 

 

 

WordPress Simple Custom Update Query

WordPress simple custom update query



global $wpdb;
$tablename = $wpdb->prefix . ‘tablename';
$sql = $wpdb->prepare(“UPDATE `”.$tablename.”` SET `status` = %s WHERE id = %d”, ‘A’, id);
$wpdb->query($sql);

Set And Get Custom Attribute Value Using Jquery

Now this is an easy way to set and get custom attribute for any element using jquery.Here  i have set custom attribute for <a> tag and named it “data-emailid”.



Example


<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Untitled Document</title>
</head>
<body>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script>
jQuery(document).ready(function(){
jQuery(‘.alerter’).click(function(){
var emailid = jQuery(this).attr(‘data-emailid’);
alert(emailid);
});
});
</script>
<a href=”#” class=”alerter” data-emailid=”test@mail.com”>Alert Mail ID</a>
</body>
</html>

how to set And get Custom Attribute Value Using Jquery



How to set and get custom attribute value using jquery



An easy way to set and get custom attribute for any element using jquery.Here  i have set custom attribute for <a> tag and named it “data-emailid”.


Example


<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Untitled Document</title>
</head>
<body>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script>
jQuery(document).ready(function(){
jQuery(‘.alerter’).click(function(){
var emailid = jQuery(this).attr(‘data-emailid’);
alert(emailid);
});
});
</script>
<a href=”#” class=”alerter” data-emailid=”test@mail.com”>Alert Mail ID</a>
</body>
</html>

PHP mail send with correct from address

PHP mail send with correct from address



<?php
function mailing($to,$subject,$message)
{
$head='<html><body><div><div style=” padding:25px 0px 30px 40px; width:100%;background:#fff;”><div>TEST</div></body></html>';
$header = ‘From: contact@yourdomain.com’ . “\r\n”;
$headers .= ‘Reply-To: contact@yourdomain.com’ . “\r\n” ;
$headers .= ‘X-Mailer: PHP/’ . phpversion();
$headers .= “MIME-Version: 1.0″ . “\r\n”;
$headers .= “Content-type:text/html;charset=iso-8859-1″ . “\r\n”;
$reply=$head.$message.$foo;
mail($to,$subject,$reply,$headers,’-f contact@yourdomain.com’);
}
?>

how to append (add) custom filter with get_post query in wordpress

Append custom filter with get_post query in wordpress


add_filter( 'posts_where', 'wpse00001_posts_where', 10, 2 );
function wpse00001_posts_where( $where, &$wp_query )
{
global $wpdb;
if ( $wpse00001_title = $wp_query->get( 'wpse00001_title' ) ) {
$where .= ' AND UPPER(' . $wpdb->posts . '.post_title) LIKE UPPER(\'%' . esc_sql( $wpdb->esc_like( $wpse00001_title ) ) . '%\')';
}
return $where;

}

Feb 17, 2016

How to upload user image using AJAX



In a script add this




function uploadimageajax()
{
jQuery('#msghere').html('');

// alert('up');

 // var file_data = jQuery('#upload_user_image').prop('files')[0];
 

//  if(1==1){

// if(  jQuery('#upload_user_image').val() != ''  ){


var data = new FormData();


/*jQuery.each(jQuery('#upload_user_image')[0].files, function(i, file) {
data.append('file-'+i, file);
});*/

jQuery.each(jQuery('#upload_user_image')[0].files, function(i, file) {
data.append('upload_user_image[]', file);
});


jQuery.ajax({
url:"<?php  echo get_template_directory_uri(); ?>/actions/actionusrimage.php",
type:'POST',
cache: false,
contentType: false,
processData: false,
data:data,  //jQuery("#profile_image_form").serialize() ,

success:function(results)
{

alert(results);
jQuery('#msghere').append(' <div class="msgsucess">Image Succesfully Updated !!</div>');
jQuery('#msgtxt').val('');
}

});

// }
//}
return false;
}



Now create  an external actionusrimage.php file & add this 

<?php @ob_start();

if(isset( $_FILES['upload_user_image'])){
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' ); //this is important

}
$uploadedfile =  $_FILES['upload_user_image'];

echo $uploadedfile ;
exit();

$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) ) {
$user_ID = get_current_user_id();
if( update_user_meta( $user_ID , 'user_profile_img', $movefile['url']  ) ){
echo 'success';
}
}
}
 ?>

Feb 16, 2016

In WordPress how to get parent child values from menu.

WordPress Loop a custom menu to get parent and child values


<?php
$menu_name = 'main_nav';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menuitems = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'DESC' ) );
?>
<nav>
<ul class="main-nav">
<?php
$count = 0;
$submenu = false;
foreach( $menuitems as $item ):
$link = $item->url;
$title = $item->title;
// item does not have a parent so menu_item_parent equals 0 (false)
if ( !$item->menu_item_parent ):
// save this id for later comparison with sub-menu items
$parent_id = $item->ID;
?>
<li class="item">
<a href="<?php echo $link; ?>" class="title">
<?php echo $title; ?>
</a>
<?php endif; ?>
<?php if ( $parent_id == $item->menu_item_parent ): ?>
<?php if ( !$submenu ): $submenu = true; ?>
<ul class="sub-menu">
<?php endif; ?>
<li class="item">
<a href="<?php echo $link; ?>" class="title"><?php echo $title; ?></a>
</li>
<?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id && $submenu ): ?>
</ul>
<?php $submenu = false; endif; ?>
<?php endif; ?>
<?php if ( $menuitems[ $count + 1 ]->menu_item_parent != $parent_id ): ?>
</li>
<?php $submenu = false; endif; ?>
<?php $count++; endforeach; ?>
</ul>
</nav>

Feb 14, 2016

get Social Share

simple method to implement social Share in a page



<?php
$url = “www.test.com”;
?>

<ul class=”social-ul-like”>
<!–<li><iframe src=”//www.facebook.com/plugins/like.php?href=https://www.facebook.com/Expiredbeans&layout=button_count&show_faces=true&width=500&action=like&font&colorscheme=light&height=23″ scrolling=”no” frameborder=”0″ style=”border:none; overflow:hidden; width:110px; height:23px;” allowTransparency=”true”></iframe></li>–>
<li >
<div id=”fb-root”></div>
<div class=”fb-like” data-send=”false” data-layout=”button_count” data-width=”1″ data-show-faces=”false” data-href=”<?php echo CONFIG::SITEURL.’Shared-‘.$donatecode ?>”></div></li>
<li><a href=”https://twitter.com/share” class=”twitter-share-button” data-count=”horizontal” data-url=”<?php echo CONFIG::SITEURL.’Shared-‘.$donatecode ?>”>Tweet</a></li>
<li><div class=”g-plusone” data-size=”medium” data-count=”true” data-href=”<?php echo CONFIG::SITEURL.’Shared-‘.$donatecode ?>”></div></li>
<li><script type=”IN/Share” data-url=”<?php echo CONFIG::SITEURL.’Shared-‘.$donatecode ?>” data-counter=”right”></script></li>
<li>
<a data-pin-zero=”true” href=”//www.pinterest.com/pin/create/button/?url='<?php echo CONFIG::SITEURL.’Shared-‘.$donatecode ?>&media=<?php echo $url ?>'” data-pin-do=”buttonBookmark” data-pin-config=”beside”><img src=”//assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_20.png” /></a>
<!– Please call pinit.js only once per page –>
<script type=”text/javascript” async src=”//assets.pinterest.com/js/pinit.js”></script>
</li>
</ul>

<script>
/*
* Async Sharing Buttons (G+, Facebook, Twitter)
* http://www.narga.net/load-social-button-javascript-asynchronously/
* Simple JavaScript function that loads the third-party scripts asynchronously and after the page loads to improve site performance.
*/
(function(doc, script) {
var js, fjs = doc.getElementsByTagName(script)[0],
frag = doc.createDocumentFragment(),
add = function(url, id) {
if (doc.getElementById(id)) {
return;
}
js = doc.createElement(script);
js.src = url;
id && (js.id = id);
frag.appendChild(js);
};
// Google+ button
add(‘http://apis.google.com/js/plusone.js’);
// Facebook SDK200103733347528
add(‘http://connect.facebook.net/en_US/all.js#xfbml=1&appId=419566788248228′, ‘facebook-jssdk’);
// Twitter SDK
add(‘http://platform.twitter.com/widgets.js’);
fjs.parentNode.insertBefore(frag, fjs);
}(document, ‘script’));
$(window).load(function () {
loadSocial();
});
function loadSocial() {
//Linked-in
if (typeof (IN) != ‘undefined’) {
IN.parse();
} else {
$.getScript(“http://platform.linkedin.com/in.js”);
}
}
</script>

Feb 13, 2016

Check User Role Matches To A Specific Role

Check user role matches to a given condition(role) and if not redirect to homepage
<?php
global $current_user; // Use global
get_currentuserinfo(); // Make sure global is set, if not set it.
if(!user_can( $current_user, “seller” )) {
$redirect_to = home_url();
wp_redirect( $redirect_to );
exit;
}
?>