Wednesday, November 11, 2020

Revamp User Profiles on the Admin Panel with Custom Contact Fields in WordPress using the "user_contactmethods" Filter

With the user_contactmethods filter, you can easily enhance the contact information fields available to your WordPress users. This filter allows you to edit the available contact methods on a user's profile page, including adding and removing fields. By customizing the contact fields, you can provide a more personalized experience for your users.

To get started, simply use the user_contactmethods filter and pass an associative array of the contact fields you want to add or remove. For example, you can add fields for Skype and Twitter usernames, or remove fields for user's Aim.

Here's an example code snippet that demonstrates how to use the user_contactmethods filter:

Parameters

  1. array $user_contact : an associative array
  2. WP_User $user: WP_User object or null if none was provided.
  3. Code Example Below: 
add_filter( 'user_contactmethods', 'modify_user_contact_methods' );
function modify_user_contact_methods( $user_contacts ) {
    // Add user contact methods
    $user_contacts['skype']  = __( 'Skype Username', 'text-domain' ); 
    $user_contacts['twitter'] = __( 'Twitter Username', 'text-domain' ); 

    // Remove user contact methods
    unset( $user_contacts['aim'] );

    return $user_contacts;
}
          

By using this filter, you can easily customize the contact fields available to your users and provide a more personalized experience on your WordPress site.


Reference

  1. https://codex.wordpress.org/Plugin_API/Filter_Reference/contactmethods 
  2. https://developer.wordpress.org/reference/functions/wp_get_user_contact_methods/

Thursday, July 2, 2020

Optimize Your Website with These Simple Code Snippets and stop 3rd Party Scripts On Google page speed insights

To stop 3rd party scripts from running on Google PageSpeed Insights use this code:

 <?php

// Stop 3rd party scripts on Google PageSpeed Insights
if (isset($_SERVER['REMOTE_ADDR']) && strpos($_SERVER['REMOTE_ADDR'], '66.249.82') === false ) :
?>
<!-- Write your code here -->
<?php endif ?>

It checks if the user's IP address is not from Google's crawler and only executes the code if the condition is true. This can help improve your website's page speed score on Google PageSpeed Insights by preventing unnecessary scripts from running during the analysis.

To use this code, simply add it to your website's header or footer. You can add your own code inside the <!-- Write your code here --> comment.

By implementing this code, you can optimize your website's performance and improve your page speed score on Google PageSpeed Insights.


To speed up the loading of Google Fonts, use the preload attribute with the link tag. Here's an example code snippet that demonstrates this optimization technique using the pre HTML tag:

<link rel="preload" href="//fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&family=Poppins:wght@300;400;500;600;700&display=swap" as="style" onload="this.onload=null;this.rel='stylesheet'" />


 

Saturday, June 13, 2020

Set Media Attribute In All Styles to Improve Your Website's Page Speed with One Simple JavaScript Code

Are you looking for ways to improve your website's page speed and performance? Look no further than this simple JavaScript code that can make a big impact on your site's speed.

<script>
    // Set media attribute to "all" for all stylesheets
    const stylesheets = document.querySelectorAll('link[rel="stylesheet"]');
    stylesheets.forEach(stylesheet => {
        stylesheet.media = 'all';
    });
</script>

The code sets the media 
attribute of all stylesheets to "all", which can improve page speed on Google PageSpeed Insights. By doing this, the browser can load all stylesheets at once, instead of waiting for them to load one by one. This can significantly reduce the time it takes for your website to load, which can improve user experience and search engine rankings.
 
To implement this code, simply add it to the end of your page, right before the closing body tag. The code uses modern JavaScript syntax, making it more efficient and easier to read than older JavaScript code.

By improving your website's page speed, you can engage visitors and keep them on your site longer. Slow-loading websites can lead to high bounce rates and lost revenue. With this simple JavaScript code, you can improve your website's performance and provide a better user experience for your visitors.

Try implementing this code on your website today and see the difference it can make in your page speed and overall performance.

Tuesday, June 2, 2020

WordPress Custom Login Form via Ajax

Create & implement custom login form via Ajax to give user login feature. Here I have developed for this a shortcode so easily put this code in any files (in theme functions.php, plugin's file) and can placed shortcode in any template file, sidebar file, page content, post content, widget.

Here I have used only 'wp_ajax_nopriv_' action hook to accept ajax request because 'wp_ajax_nopriv_' action hook is accept only requests are send via frontend pages (non-logged in users).

# Create a shortcode [login_form] so we can put it wherever we want
# and this put functions.php or your desire plugin

add_shortcode('login_form', 'pkt_login_form');
function pkt_login_form($attr) {
	/* define desire key index */
    $attr = shortcode_atts( array(
		
	), $attr );

    extract($attr);

    ob_start();
    require 'login.php';
    $return = ob_get_clean();
	return $return;
}


# here login.php page code 
<form action="" id="login_form" method="POST">
    <input name="pkt_login" type="hidden" value="1" />
        

    <div class="form-check">
        <label>Email Address</label>
        <input name="email" placeholder="Your registered email address" required="" type="email" />
    </div>

    <div class="form-check">
        <label>Password</label>
        <input name="password" required="" type="password" />
    </div>

    <div class="form-check">
        <input class="form-check-input" name="remember" type="checkbox" value="1" />
        <label>Keep me logged in</label>
        <a href="&lt;?php echo home_url('wp-login.php?action=lostpassword') ?&gt;" id="forget_pass_btn">Forget Password?</a>
    </div>
    <div class="btn_mainstyle">
        <button class="btn_style btn_submit" type="submit">Log in</button>
        &nbsp;
        <span class="spinner-border text-primary" style="display: none; height: 20px; width: 20px;"></span>
    </div>
</form>


<script>
	jQuery('#login_form').submit(function (e) {
		e.preventDefault();
		let th = jQuery(this);
		let data = th.serialize();
		th.find('.btn_mainstyle span').show()
		jQuery('.response-msg').text('').hide()
		jQuery('.btn_submit').attr('disabled', true)

		jQuery.ajax({
			url: '<?php echo admin_url('admin-ajax.php') ?>',
			type: 'POST',
			dataType: 'json',
			data: {
				action: 'pkt_login',
				data: data
			},
			success: function (res) {
				th.find('.btn_mainstyle span').hide();
				jQuery('.response-msg').html(res.msg).show();

				if (res.status) {
					jQuery('.response-msg').removeClass('text-danger').addClass('text-success');
					setTimeout(() => {
						window.location.href = res.redirectTo;
					}, 1500);
				} else {
					jQuery('.response-msg').removeClass('text-success').addClass('text-danger');
					jQuery('.btn_submit').attr('disabled', false)
				}

			},
			error: function (x, h) {
				console.log(x, h);
				th.find('.btn_mainstyle span').hide();
				jQuery('.response-msg').html('An error has occured during Login')
					.show().addClass('text-danger');
				jQuery('.btn_submit').attr('disabled', false)
			}
		});
		return false;
	});
</script>



# now add a ajax handler to receive ajax request
# here need to use only 'wp_ajax_nopriv_' action 

add_action('wp_ajax_nopriv_pkt_login', 'pkt_login');
function pkt_login() {
	$response = ['status' =&gt; false];
	if (empty($_POST['data']))
		$response['msg'] = 'Please flll out the form!!';
	else {
		parse_str($_POST['data'], $data);
		if (! wp_verify_nonce( $data['pkt_form_nonce'], 'pkt_nonce' )) {
			$response['msg'] = 'Our Site is protected!!';

		} else {
			$user_email = sanitize_email($data['email']);
			$password = $data['password'];

			if (! is_email( $user_email ) ) {
				$response['msg'] = 'Error: The email address isn&#8217;t correct. or already registered.';

			} elseif (!email_exists( $user_email )) {
				$response['msg'] = 'Error: The email address is not registered.';

			} else {
				$creds = array(
					'user_login'    =&gt; $user_email,
					'user_password' =&gt; $password,
					'remember'      =&gt; empty($data['remember']) ? false : true
				);

				$user = wp_signon( $creds, true );
				if ( is_wp_error( $user ) ) {
					$response['msg'] = $user-&gt;get_error_message();
				} else {
					$response['status'] = true;
					$response['redirectTo'] = site_url();
					$response['msg'] = 'Login successfully.';
				}
			}
		}
	}
	echo json_encode($response);
	wp_die();
}

Tuesday, April 14, 2020

Convert user time to UTC time


/**
 * Convert user's local time to UTC time
 */
function dateTime_local_to_utc($time, $timezone, $abbr = false) {
    //target time zone
    if ($abbr) {
        $t = timeStandardToTimeZone($timezone);
        $timezone = $t['timezone_id'];
    }

    $userTimezone = new DateTimeZone($timezone);
    $userTime = new DateTime('now', $userTimezone);

    // time in seconds, based on UTC
    $offset = $userTime->getOffset();

    // get server timeZone first
    $server_timezone = date_default_timezone_get();
    // set server timeZone provided via user
    date_default_timezone_set($timezone);

    // get UTC time
    $time = date('Y-m-d H:i:s', strtotime($time) - $offset);

    // now set server timeZone default
    date_default_timezone_set($server_timezone);
    return $time;
}

if (!function_exists('timeStandardToTimeZone')) {
    function timeStandardToTimeZone($ts)
    {
        $timezone_abbreviations = DateTimeZone::listAbbreviations();
        if (!empty($timezone_abbreviations[strtolower($ts)])) {
            return $timezone_abbreviations[strtolower($ts)][0];
        }

        return $ts;
    }
}


Thursday, April 2, 2020

Add Cookies Alert with AngularJs

Html code
<div class="cookieinfo-flag" data-ng-if="cookie_flag" style="background: #ea5031; bottom: 0px; color: white; font-family: "verdana", "arial", sans-serif; font-size: 14px; height: auto; left: 0px; line-height: 21px; min-height: 21px; opacity: 1; padding: 8px 18px; right: 0px; text-align: left; z-index: 2147483647;">
  <div class="cookieinfo-close" data-ng-click="setCookieFlag()" style="background: #f1d600; border-radius: 5px; color: black; cursor: pointer; display: block; float: right; margin-left: 5px; min-width: 100px; padding: 5px 8px; text-align: center;">Got it!</div>
  >span style="display: block; padding: 5px 0 5px 0;">We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies. <a href="https://wikipedia.org/wiki/HTTP_cookie/#" style="color: #f1d600; text-decoration: none;">More info</a></span>
</div>
Angular js code
var app = angular.module("myApp", []);  
app.controller("mainController", function($scope, $cookies) {
    /**
     * Check CookieFlag is set
     * if not then show flag alert (.cookieinfo-flag)
     */
    $scope.cookie_flag = true;
    if ($cookies.get('CookieFlag')) {
        $scope.cookie_flag = false;
    }
    /**
     * Set illusparkCookieFlag and hide flag alert (.cookieinfo-flag)
     */
    $scope.setCookieFlag = function() {
        $cookies.put('CookieFlag', true, {
            'expires': new Date('01/01/9999'),
            'path': '/'
        });
        $scope.cookie_flag = false;
    };

Thursday, February 6, 2020

Paid Memberships Pro LevelMeta (Addon)

/*
Plugin Name: Paid Memberships Pro LevelMeta (Addon)
Plugin URI: https://pk-techie.blogspot.com/2020/02/paid-memberships-pro-levelmeta-addon.html
Description: Useful to get, update, delete memership level meta data like wordpress meta data
Author: PrakharKant
Version: 1.0
Author URI: https://pk-techie.blogspot.com/
*/


register_activation_hook( __FILE__, 'pkLm_plugin_activate' );
function pkLm_plugin_activate(){

    // Require parent plugin
    if ( ! is_plugin_active( 'paid-memberships-pro/paid-memberships-pro.php' ) and current_user_can( 'activate_plugins' ) ) {
        // Deactivate the plugin
        deactivate_plugins(__FILE__);
       
        // Throw an error in the wordpress admin console
        $error_message = __('This plugin requires Paid Memberships Pro plugin to be active!');

        die($error_message);

    }
}


function pk_update_pmprolevel_meta($object_id, $meta_key, $meta_value) {
    global $wpdb;

    $table = $wpdb->pmpro_membership_levelmeta;
    $column = 'pmpro_membership_level_id';

    $object_id = absint( $object_id );

    if ( ! $object_id ) { return false; }

    // expected_slashed ($meta_key)
    $meta_key = wp_unslash($meta_key);
    $meta_value = wp_unslash($meta_value);
    $meta_value = sanitize_meta( $meta_key, $meta_value, $column );
    $meta_value = maybe_serialize( $meta_value );

    $meta_ids = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT meta_id FROM $table WHERE meta_key = %s AND $column = %d",
                        $meta_key,
                        $object_id
                    )
                );

    if ( empty( $meta_ids ) ) {
        $result = $wpdb->insert( $table, array(
            $column => $object_id,
            'meta_key' => $meta_key,
            'meta_value' => $meta_value
        ) );

        $meta_id = (int) $wpdb->insert_id;
        return $meta_id;
    }

    $data  = compact( 'meta_value' );
    $where = array( $column => $object_id, 'meta_key' => $meta_key );

    $result = $wpdb->update( $table, $data, $where );

    var_dump($result);
}


function pk_delete_pmprolevel_meta($object_id, $meta_key, $meta_value = '') {
    global $wpdb;

    $table = $wpdb->pmpro_membership_levelmeta;
    $column = 'pmpro_membership_level_id';

    if ( ! $meta_key || ! is_numeric( $object_id ) ) {
        return false;
    }

    $object_id = absint( $object_id );

    if ( ! $object_id ) { return false; }

    // expected_slashed ($meta_key)
    $meta_key = wp_unslash($meta_key);
    $meta_value = wp_unslash($meta_value);
    $meta_value = maybe_serialize( $meta_value );

    $query = $wpdb->prepare(
        "DELETE FROM $table WHERE $column = %d AND meta_key = %s ",
        $object_id,
        $meta_key
    );

    if ( '' !== $meta_value && null !== $meta_value && false !== $meta_value )
        $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );

    $count = $wpdb->query($query);

    if ( !$count )
        return false;

    return true;
}


function pk_get_pmprolevel_meta($object_id, $meta_key = '', $single = false) {
    global $wpdb;

    $table = $wpdb->pmpro_membership_levelmeta;
    $column = 'pmpro_membership_level_id';

    if ( ! is_numeric( $object_id ) ) {
        return false;
    }

    $object_id = absint( $object_id );

    if ( ! $object_id ) { return false; }

    $query = "SELECT * FROM $table WHERE $column = $object_id";

    if( !$meta_key ) {
        $result = $wpdb->get_results($query);
    }

    $query .= " AND meta_key = '$meta_key'";
    $result = $wpdb->get_row($query);

    if( !$result )
        return false;

    if( !$single )
        return $result;

    $value = maybe_unserialize($result->meta_value);
    return $value;
}

/*
* delete all meta data on deletion of membership deletion
*/

add_action('pmpro_delete_membership_level', function($level_id){
    global $wpdb;

    $table = $wpdb->pmpro_membership_levelmeta;
    $column = 'pmpro_membership_level_id';

    $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $table WHERE $column = %d ", $level_id ));
   
    foreach ( $meta_ids as $mid ) {
        $result = (bool) $wpdb->delete( $table, array( 'meta_id' => $mid ) );
    }

}); 

Get current page url in javascript

var curPageURL = window.location.origin + window.location.pathname;

Thursday, January 30, 2020

Validate given string is JSON

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

Convert a JavaScript Object to FormData Object

/* takes a {} object and returns a FormData object */
function objectToFormData(obj, form, namespace) {
    var fd = form || new FormData();
    var form_key;
    for (var property in obj) {
        if (obj.hasOwnProperty(property) && property != '$$hashKey') {
            if (namespace) {
                form_key = namespace + '[' + property + ']';
            } else {
                form_key = property;
            }
            /*if the property is an object, but not a File,*/
            /*use recursivity.*/
            if (obj[property] instanceof Date) {
                fd.append(form_key, obj[property].toISOString());
            } else if (typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
                objectToFormData(obj[property], fd, form_key);
            } else {
                /*if it's a string or a File object*/
                if (!empty(obj[property])) {
                    fd.append(form_key, obj[property]);
                }
            }
        }
    }
    return fd;
}

Check given variable is Empty ?

/* check variable contain empty values or not */
function empty(data) {
    if (typeof(data) == 'number' || typeof(data) == 'boolean') {
        return false;
    }
    if (typeof(data) == 'undefined' || data === null) {
        return true;
    }
    if (typeof(data.length) != 'undefined') {
        /*if(/^[\s]*$/.test(data.toString())) {
        return true;
        }*/
        return data.length == 0;
    }
    if (data instanceof File) {
        return false;
    }
    var count = 0;
    for (var i in data) {
        /* if (data.hasOwnProperty(i)) { */
        count++;
        /* } */
    }
    return count == 0;
}

Wednesday, January 29, 2020

Send Post Request without response

function post_without_wait12($url, $params)
{               
    foreach ($params as $key => &$val) {
        if (is_array($val)) $val = implode(',', $val);
        $post_params[] = $key.'='.urlencode($val);
    }
   
    $post_string = implode('&', $post_params);
   
    $parts=parse_url($url);
    $fp = fsockopen($parts['host'],
    isset($parts['port'])?$parts['port']:80,
    $errno, $errstr, 30);
    $out = "POST ".$parts['path']." HTTP/1.1\r\n";
    $out.= "Host: ".$parts['host']."\r\n";
    $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out.= "Content-Length: ".strlen($post_string)."\r\n";
    $out.= "Connection: Close\r\n\r\n";
    if (isset($post_string)) $out.= $post_string;
    fwrite($fp, $out);
    fclose($fp);
}

Is PHP Session Start ?

if ( pk_is_session_started() === FALSE ) session_start();


function pk_is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}



Tuesday, January 28, 2020

WordPress Check Dependent Plugin Is Installed ?

register_activation_hook( __FILE__, 'pkLm_plugin_activate' );
function pkLm_plugin_activate(){
    // Require parent plugin
    if ( ! is_plugin_active( `'plugin_folder/plugin_file'` ) and current_user_can( 'activate_plugins' ) ) {
        // Deactivate the plugin
        deactivate_plugins(__FILE__);
    
        // Throw an error in the wordpress admin console
        $error_message = __('This plugin requires <a href="#">`Dependent Plugin Name`</a> plugin to be active!');
        die($error_message);
    }

Remove index.php from URL

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]