Enter your keyword

Wordpress

How to use Instagram API in Wordpress Shortcode

/*  Following funt in theme functions.php file */
add_shortcode('instagram_feeds', 'instagram_feeds_shortcode');
function rudr_instagram_api_curl_connect( $api_url ){
	$connection_c = curl_init(); // initializing
	curl_setopt( $connection_c, CURLOPT_URL, $api_url ); // API URL to connect
	curl_setopt( $connection_c, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
	curl_setopt( $connection_c, CURLOPT_TIMEOUT, 20 );
	$json_return = curl_exec( $connection_c ); // connect and get json data
	curl_close( $connection_c ); // close connection
	return json_decode( $json_return ); // decode and return
}

function instagram_feeds_shortcode( $atts ) {
    extract( shortcode_atts( array(
        
    ), $atts, 'domain' ) );
  
	$outputs = '';
	$instagram_access_token = 'Instagram Access Token';
	$return = rudr_instagram_api_curl_connect("https://api.instagram.com/v1/users/self/media/recent?access_token=".$instagram_access_token."&count=4");
	$outputs .='<ul>';
 		foreach ($return->data as $instagrampost) { 
  			$outputs .= '<li> <figure><img src="'. $instagrampost->images->standard_resolution->url.'" /></figure></li>';
		}
	$outputs .='</ul>';
return $outputs;     
}

How to Disable Search Page

function fb_filter_query( $query, $error = true ) {
    
    if ( is_search() ) {
        $query->is_search = false;
        $query->query_vars[s] = false;
        $query->query[s] = false;
        
        // to error
        if ( $error == true )
            $query->is_404 = true;
    }
}

add_action( 'parse_query', 'fb_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

How to Remove widgets in sidebar

add_action( 'widgets_init', 'remove_register_sidebar_widgets', 11 );
function remove_register_sidebar_widgets(){
	unregister_sidebar( 'sidebar-1' );
	unregister_sidebar( 'sidebar-2' );
	unregister_sidebar( 'sidebar-3' );
}

ACF Repeater field value in WP_Query

/*  Add in theme functions.php file */
function class_schedule_posts_where( $where ) {
   $where = str_replace("meta_key = 'class_schedule_$", "meta_key LIKE 'class_schedule_%", $where);
   return $where;
}
add_filter( 'posts_where', 'class_schedule_posts_where' );

/* WP_Query  */
$arr_posts = array(
	   'posts_per_page' => -1,
	   'post_type'		=> 'class',
	   'post_status' 	=> array('publish'),
	   'meta_key'      	=> 'class_schedule_$_class_time',
	   'orderby'     	=> 'meta_value_num',
	   'order'       	=> 'ASC',
	   'meta_query'     => array(
			                array(
			                  'key'     => 'class_schedule_$_class_day',
			                  'compare' => '=',
			                  'value'   => $arrayDays[$d],
			                ),
	             		 ),          
	    );
$wp_query = new WP_Query($arr_posts); 

How to Order by Advanced Custom field in WP_QUERY

function my_pre_get_posts( $query ) {
	// do not modify queries in the admin
	if( is_admin() ) {	
		return $query;	
	}
	
	// only modify queries for 'event' post type
	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'event' ) {
		$query->set('orderby', 'meta_value');	
		$query->set('meta_key', 'p_start_date');	 
		$query->set('order', 'ASC'); 		
	}
		// return
	return $query;

}

add_action('pre_get_posts', 'my_pre_get_posts');

How to Add Option Page in Advanced Custom Fields Plugin

 if(function_exists(acf_add_options_page))
{
	acf_add_options_sub_page(array(
	  'page_title'  => 'Theme General Settings',
	  'menu_title' => 'Theme Settings',
	  'parent_slug' => 'themes.php',
	  'menu_slug'  => 'theme-general-settings',
	  'capability' => 'edit_posts',
	  'redirect'  => false
	));
}

How to add radio button Metabox in WordPress Custom and Default Post Types

add_action( 'add_meta_boxes', 'post_disable_enable' );
function post_disable_enable() {
add_meta_box('post_disable_enable', 'Post Disable Enable', 'post_disable_enable_meta', 'post' );
}
function post_disable_enable_meta( $post ) {
	wp_nonce_field( 'post_disable_enable', 'post_disable_enable_nonce' );
	$value = get_post_meta( $post->ID, 'post_disable_enable', true );
	echo '<input type="radio" name="post_disable_enable" value="disable" ';
    	if($value=='disable') {
			echo 'checked';
		}
	'> Disable<br/>';
	echo '<input type="radio" name="post_disable_enable" value="enable" ';
		if($value=='enable') {
			echo 'checked';
		}
	echo '> Enable<br/>';
  }
  
add_action( 'save_post', 'disable_enable_save_meta_box_data' );
function disable_enable_save_meta_box_data( $post_id ) {
	// Check if our nonce is set.

	if ( !isset( $_POST['post_disable_enable_nonce'] ) ) {
  	return;
  	}
	// Verify that the nonce is valid.
	if ( !wp_verify_nonce( $_POST['post_disable_enable_nonce'], 'post_disable_enable' ) ) {
	return;
	}
	// If this is an autosave, our form has not been submitted, so we don't want to do anything.
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
  	return;
  	}
  	// Check the user's permissions.
	if ( !current_user_can( 'edit_post', $post_id ) ) {
	return;
	}
  	// Sanitize user input.
  	$new_meta_value = ( isset( $_POST['post_disable_enable'] ) ? sanitize_html_class( $_POST['post_disable_enable'] ) : '' );
	// Update the meta field in the database.
	update_post_meta( $post_id, 'post_disable_enable', $new_meta_value );
  }

How to Change Admin URL Without Plugin

Step 1: Configuration define in wp-config.php

define('WP_ADMIN_DIR', 'private-area');
define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . WP_ADMIN_DIR); 

Step 2: Add a function in your theme functions.php file

add_filter('site_url',  'change_wpadmin_url', 10, 3);  
function change_wpadmin_url( $url, $path, $orig_scheme ) {
	$old_admin_url  = array( "/(wp-admin)/");
	$admin_dir = WP_ADMIN_DIR;
	$new_admin_url  = array($admin_dir);
	return preg_replace( $old_admin_url, $new_admin_url, $url, 1); 
}

Step 3: Add a line to .htaccess file

RewriteRule ^private-area/(.*) wp-admin/$1?%{QUERY_STRING} [L]

Post Per Page on Search and Category Page

add_action( 'pre_get_posts',  'set_posts_per_page'  );
function set_posts_per_page( $query ) {
    global $wp_the_query;
    if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_search() ) ) {
    	$query->set( 'posts_per_page', 10 );
    }
    elseif ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_category() ) ) {
    	$query->set( 'posts_per_page', 10 );
    }
    return $query;
} 
 

Comment Like and Dislike Function in Wordpess

// Create Table in your Databse SQL
CREATE TABLE custom_comment_likes(
    id INT NOT NULL AUTO_INCREMENT,
    comment_id INT NOT NULL,
    ip_address VARCHAR (255),
    status INT NOT NULL,
    PRIMARY KEY (id)
);
function dsweb_comment_like_dislike(){
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    global $wpdb;
    $like_count = $wpdb->get_var( "SELECT * FROM custom_comment_likes WHERE `ip_address` = '".$ip."' AND `comment_id` = '".$_POST[id]."'");
    $count = $wpdb->num_rows;
    if(!$count > 0){
        $wpdb->insert( 'custom_comment_likes',  array(  'ip_address' => $ip, 'comment_id' => $_POST[id] , 'status' => $_POST[status]),  array( '%s', '%d' ,'%d') );
    }else{
        $wpdb->update('custom_comment_likes', array( 'status' => $_POST[status]), array( 'comment_id' => $_POST[id] ,'ip_address' => $ip), array('%d' ),array( '%d','%s' ) );
    }
    $like_query = $wpdb->get_results("SELECT * FROM custom_comment_likes WHERE `comment_id` = '".$_POST[id]."' AND `status` = '1'");
    $like = $wpdb->num_rows;
    $dislike_query = $wpdb->get_results("SELECT * FROM custom_comment_likes WHERE `comment_id` = '".$_POST[id]."' AND `status` = '0'");
    $dislike = $wpdb->num_rows;
    $arg['success']['like'] = $like;
    $arg['success']['dislike'] = $dislike;
    return $arg;
}

How to get previous and next post of given post id in Wordpress

function getPreviousNext($currenPostID){
    $postids = array();
    global $post;
    $post = get_post($currenPostID);
    $previous_post = get_previous_post();
    $next_post = get_next_post();
    $nextPost = get_post($next_post->ID);
    $prevPost = get_post($previous_post->ID);
    $postids["nextSlug"] = $prevPost->post_name;
    $postids["prevSlug"] = $nextPost->post_name;
    $postids["prevlink"] = $next_post->ID;
    $postids["nextlink"] = $previous_post->ID;
    return $postids;
}

How to Disable Plugin Deactivation in Wordpress

add_filter( 'plugin_action_links', 'disable_plugin_deactivation', 10, 4 );
function disable_plugin_deactivation( $actions, $plugin_file, $plugin_data, $context ) {
    // Remove edit link for all
    if ( array_key_exists( 'edit', $actions ) )
        unset( $actions['edit'] );
    // Remove deactivate link for crucial plugins
    if ( array_key_exists( 'deactivate', $actions ) && in_array( $plugin_file, array(
        'json-rest-api/plugin.php'
    )))
        unset( $actions['deactivate'] );
    return $actions;
}

How to Change Preview Page link in Wordpress

function dswebsolutions_preview_link() {
    $site_url = site_url();
    $mydir = $site_url.'/preview-page/'.get_the_ID(); 
    return "$mydir";
}
add_filter( 'preview_post_link', 'dswebsolutions_preview_link' ); 

How to Remove Query String from Static Resources in Wordpress

function remove_cssjs_ver( $src ) {
    if( strpos( $src, '?ver=' ) )
    $src = remove_query_arg( 'ver', $src );
    return $src;
}
add_filter( 'style_loader_src', 'remove_cssjs_ver', 10, 2 );
add_filter( 'script_loader_src', 'remove_cssjs_ver', 10, 2 );

How to get terms in Wordpress

function get_year_taxonomy_child() {
    $values = get_terms('events-years');
    foreach ($values as $value) {
    $categories[] = array('name'=>$value->name,'slug'=>$value->slug);
    }
  $output = '';
    $output .= '<div id="dd11" class="wrapper-dropdown-11 dropdown_list" tabindex="4">
  <span>'.__('All Years','vh').'</span>
  <ul class="dropdown">';
    foreach ( $categories as $cat ) {
    $output .= '<li><a href="#">'.$cat['name'].'</a><input type="hidden" value="'.$cat['slug'].'"></li>';
    }
  $output .= '</ul>
  </div>';
return $output;
    }

How to add Adding Registration fields to the Woocommerce Registration form

 //Add Registration fields to the form 
add_filter( 'register_form', 'adding_custom_registration_fields' );
function adding_custom_registration_fields( ) {
        echo '<div class="form-row form-row-wide"><label for="reg_role">'.__('Role', 'woocommerce').' <span class="required">*</span></label>';
        echo '<select name="wp_capabilities">
        <option value="customer">Customer</option>
        <option value="designer">Designer</option>
        </select>';
        echo '</div>';
 }
  
//Validation registration form  after submission using the filter registration_errors
add_filter('registration_errors', 'registration_errors_validation', 10,3);
function registration_errors_validation($reg_errors, $sanitized_user_login, $user_email) {
    global $woocommerce;
    extract($_POST); // extracting $_POST into separate variables
    if($wp_capabilities == '' ) {
    $woocommerce->add_error( __( 'Please, fill in all the required fields.', 'woocommerce' ) );
    }
    return $reg_errors;
}
//Updating use meta after registration successful registration
add_action('woocommerce_created_customer','adding_extra_reg_fields');
function adding_extra_reg_fields($user_id) {
extract($_POST);
// update user role using wordpress function
wp_update_user( array ('ID' => $user_id, 'role' => $wp_capabilities ) ) ;
}

How to Add/Remove New Columns on wp-admin Products Listing Page

// ADD NEW COLUMN
add_filter( 'manage_edit-product_columns', 'show_product_columns',15 );
function show_product_columns($columns){
//remove column
        unset($columns['sku']);
        unset($columns['product_tag']);
        unset($columns['product_type']);
//add column
        $columns['author'] = __( 'Author');
        return $columns;
}
add_action( 'manage_product_posts_custom_column', 'product_column_author', 10, 2 );
function product_column_author( $column, $postid ) {
    if ( $column == 'author' ) {
    echo $postid;
    }
}