SOFTTOUCH API INTEGRATION WITH WORDPRESS USING SOAP(CURL METHOD)

Hi guys,
here is the code snippete to Integrate third-party API(Web Service) in WordPress, This is the post related to Integrate the SoftTouch API, using the SOAP client with cURL method. (using only the API Access Token method)

To initiate, connection, and get products from SoftTouch API, following is the code snippet:

$authToken = 'your-api-access-token';  
$base_url = 'your-api-base-url-with-account-id'; //eg. https://api.softtouch.eu/1/accounts/your-account-id-here/
base_url .= 'pass-your-api-requet-here'; //eg. if you want to get first 100 products then use, products?take=100
$httpRequest = curl_init();
curl_setopt($httpRequest, CURLOPT_HTTPHEADER, array('Authorization: ' . $authToken, 'Content-Type: application/json'));
curl_setopt($httpRequest, CURLOPT_URL, $base_url);
curl_setopt($httpRequest, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($httpRequest);
if ($response1 === FALSE){
    die(curl_error($httpRequest));
}
curl_close($httpRequest);
$product_arr = json_decode($response);

thats it, in the $product_arr variable you will get first 100 products array response.

Note: Similarly, you can use different types of API requests according to your requirements.

Thank you,

CREATE CUSTOM POST TYPE IN WP THEME

Hi guys,
here is the code snippet to create custom post type in wp theme

to create custom post type in wp theme, add the following code to your theme’s functions.php file.

function ucs_custom_post_products() {
    $labels = array(
        'name' => _x('Products', 'post type general name', 'ucs'),
        'singular_name' => _x('Products', 'post type singular name', 'ucs'),
        'add_new' => _x('Add New Products', 'book', 'ucs'),
        'add_new_item' => __('Add New Products', 'ucs'),
        'edit_item' => __('Edit Products', 'ucs'),
        'new_item' => __('New Products', 'ucs'),
        'view_item' => __('View Products', 'ucs'),
        'search_items' => __('Search Products', 'ucs'),
        'not_found' =>  __('No Products found', 'ucs'),
        'not_found_in_trash' => __('No Products found in Trash', 'ucs'), 
        'parent_item_colon' => ''
    );      
    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true, 
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => null,
        'has_archive' => true,
        'supports' => array('title', 'editor', 'thumbnail'),
        'menu_icon' => 'dashicons-cart'
    );      

    register_post_type( 'products', $args );

    $labels = array(              
      'name' => _x( 'Products Categories', 'taxonomy general name' ),
      'singular_name' => _x( 'Products Category', 'taxonomy singular name' ),
      'search_items' =>  __( 'Search Products Categories' ),
      'all_items' => __( 'All Products Categories' ),
      'parent_item' => __( 'Parent Products Category' ),
      'parent_item_colon' => __( 'Parent Products Category:' ),
      'edit_item' => __( 'Edit Products Category' ), 
      'update_item' => __( 'Update Products Category' ),
      'add_new_item' => __( 'Add New Products Category' ),
      'new_item_name' => __( 'New Products Category Name' ),
       
    );

    register_taxonomy(
        'productscats',
        'product',
        array(
            'public'=>true,
            'hierarchical' => true,
            'labels'=> $labels,
            'query_var' => 'productscats',
            'show_ui' => true,
            'rewrite' => array( 'slug' => 'productscats', 'with_front' => false ),
        )
    );        
}                                  
add_action('init', 'ucs_custom_post_products');

Thank You.

CUSTOM IMAGE RESIZE/CROPPING IN WP

Hi guys,
here is the code snippet to custom image resize/cropping in wp

to custom pagination for the custom image resize/cropping in wp, add the following code to your theme’s functions.php file.

function custom_resize($url, $width, $height = null, $crop = null, $single = true) {
    if (!$url OR !$width)
    return false;
 
    $upload_info = wp_upload_dir();
    $upload_dir = $upload_info['basedir'];
    $upload_url = $upload_info['baseurl'];
 
    if (strpos($url, $upload_url) === false)
        return false;
 
    $rel_path = str_replace($upload_url, '', $url);
    $img_path = $upload_dir . $rel_path;
 
    if (!file_exists($img_path) OR !getimagesize($img_path))
    return false;
 
    $info = pathinfo($img_path);
    $ext = $info['extension'];
    list($orig_w, $orig_h) = getimagesize($img_path);
 
    $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop);
    $dst_w = $dims[4];
    $dst_h = $dims[5];
 
    $suffix = "{$dst_w}x{$dst_h}";
    $dst_rel_path = str_replace('.' . $ext, '', $rel_path);
    $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}";
 
    if (!$dst_h) {
        $img_url = $url;
        $dst_w = $orig_w;
        $dst_h = $orig_h;
    }
    elseif (file_exists($destfilename) && getimagesize($destfilename)) {
        $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}";
    }
    else {
        if (function_exists('wp_get_image_editor')) {
 
            $editor = wp_get_image_editor($img_path);
 
            if (is_wp_error($editor) || is_wp_error($editor->resize($width, $height, $crop)))
                return false;
 
            $resized_file = $editor->save();
 
            if (!is_wp_error($resized_file)) {
                $resized_rel_path = str_replace($upload_dir, '', $resized_file['path']);
                $img_url = $upload_url . $resized_rel_path;
            } else {
                return false;
            }
        } else {
 
            $resized_img_path = image_resize($img_path, $width, $height, $crop);
            if (!is_wp_error($resized_img_path)) {
                $resized_rel_path = str_replace($upload_dir, '', $resized_img_path);
                $img_url = $upload_url . $resized_rel_path;
            } else {
                return false;
            }
        }
    }
 
    if ($single) {
        $image = $img_url;
    } else {
        $image = array(
            0 => $img_url,
            1 => $dst_w,
            2 => $dst_h
        );
    }
    return $image;
}
 
//added theme-support for image cropping
if (function_exists('add_theme_support')) {
    add_theme_support('post-thumbnails');
    add_image_size('large-full', 1920, 781, true); 
    add_image_size('full', 1180, 440, true); 
    add_image_size('large', 950, 480, true);
    add_image_size('medium', 440, 330, true);
    add_image_size('thumbnail', 250, 187, true);
}

use custom image cropping function in image tag

// custom_resize($image_url,600,400,true);
// width = 600, height = 400, true = hard crop
<img src="'.custom_resize( $comimage, 450, 250, true )'">

Thank you,

CREATE CUSTOM META-BOX FOR WP POSTS AND PAGES USING CMB2

here is the code snippete to integrate/include CMB2 library and custom-meta-box fields

to integrate/include CMB2 library and custom-meta-box fields, add the following code to your theme’s functions.php file.

add_action( 'init', 'be_initialize_cmb_meta_boxes', 9999 );
function be_initialize_cmb_meta_boxes() {
    if ( !class_exists( 'cmb_Meta_Box' ) ) {
        require_once( get_template_directory() ."/customs/CMB2/init.php" );
    }
}
require ( get_template_directory() . "/customs/CMB2/metaboxes.php");

here you can find the customs folder, add this customs folder in your custom theme.
https://github.com/vinayakz/REDUX-FRAMEWORK-AND-CMB2/tree/master/CMB2

in the file /customs/CMB2/metaboxes.php
on line 480, there is custom post’s sample meta-box
on line 500, there is custom page-template’s sample meta-box

for reference of meta-fields, you can check this file /customs/CMB2/example-functions.php

Thank you,

CREATE CUSTOM THEME OPTIONS PANEL FOR WP CUSTOM THEME USING REDUX FRAMEWORK

Hi guys,
here is the code snippete custom Theme Options Panel for wp custom theme using Redux Framework

to integrate/include Redux Framework, add the following code to your theme’s functions.php file.

require_once (dirname(__FILE__) . '/redux/redux-framework.php');
if ( class_exists( 'Redux' ) ) {
    require_once (dirname(__FILE__) . '/redux/sample/barebones-config.php');
}

here you can find the redux folder, add this redux folder in your custom theme.

https://github.com/vinayakz/REDUX-FRAMEWORK

in the file /redux/sample/barebones-config.php
on line 200, there is demo theme options for header and footer

for reference of all in-built fields, you can check this file /redux/sample/sample-config.php

Thank you,

HOW TO INCLUDE CSS AND JS FILES IN CUSTOM WORDPRESS THEME

Hi guys,
here is the code snippete to include CSS and JS files in your custom wp theme

to include JS files(include JS files to front-end), add the following code to your theme’s functions.php file.

add_action( 'wp_enqueue_scripts', 'mytheme_load_scripts' );
function mytheme_load_scripts(){
    wp_register_script('my-custom-js', get_template_directory_uri() . '/js/my-custom-js.js', false, true);
    wp_enqueue_script('my-custom-js');
}

to include CSS files(include CSS files to front-end), add the following code to your theme’s functions.php file.

add_action('wp_print_styles', 'mytheme_load_css');
function mytheme_load_css(){
    wp_register_style('my-custom-css', get_template_directory_uri() . '/css/my-custom.css');    
    wp_enqueue_style('my-custom-css');
}

to include CSS files(include CSS files to wp-admin/backend), add the following code to your theme’s functions.php file.

add_action( 'admin_enqueue_scripts', 'mytheme_theme_admin_styles', 11 );
function mytheme_theme_admin_styles() {
    wp_register_style( 'admin-styles', get_stylesheet_directory_uri() . '/css/admin-styles.css' );
    wp_enqueue_style( 'admin-styles' );
}

to include JS files(include JS files to wp-admin/backend), add the following code to your theme’s functions.php file.

add_action( 'admin_enqueue_scripts', 'mytheme_theme_admin_script' );
function mytheme_theme_admin_script() {
        wp_register_script('admin-scripts', get_template_directory_uri() . '/js/admin-scripts.js',false,true);
    wp_enqueue_script('admin-scripts');
}

How to Automatically logout inactive user using PHP

session_start();
if(isset($_POST['type']) && $_POST['type']=='ajax'){
	if((time()-$_SESSION['LAST_ACTIVE_TIME'])>10){ 
		echo "logout";
	}
}else{
	if(isset($_SESSION['LAST_ACTIVE_TIME'])){
		if((time()-$_SESSION['LAST_ACTIVE_TIME'])>10){
			header('location:logout.php');	
			die();
		}
	}
	$_SESSION['LAST_ACTIVE_TIME']=time();
	if(!isset($_SESSION['IS_LOGIN'])){
		header('location:index.php');
		die();
	}
}

Image resize function in PHP

if(isset($_FILES['proof']) &amp;&amp; $_FILES['proof']['type'] == 'image/jpeg' &amp;&amp; ($_FILES['profile']) &amp;&amp; $_FILES['profile']['type'] == 'image/jpeg')
    {
       $temp_file1 = $_FILES['proof']['tmp_name'];
        $temp_file2 = $_FILES['profile']['tmp_name'];
        $target_dir = "../main_tmp/dist/vendor/";            
        $file1 = $_FILES['proof']['tmp_name'];
        $file2 = $_FILES['profile']['tmp_name'];
        $name = $vencode.'.jpeg';        
        $width = 433; // Custom Width for Resized Image
        $height = 320;  // Custom Height for Resized Image
        $resized_image1 = resize_image($file1,$width,$height);
        $resized_image2 = resize_image($file2,$width,$height);
        
        $query = mysqli_query($con,"insert into photo values('$name','$name')");
        if($query)
        {
            move_uploaded_file($file1,"../main_tmp/dist/vendor/".$name);
            move_uploaded_file($file2,"../main_tmp/dist/vendor/profile/".$name);
            echo '
                    alert("Details Added Successfully...!");document.location="vendor_view.php";
                    <!-- history.back(); -->
                ';
            

        }else
        {
            echo '
                alert("Failed to Submited...");history.back();
                ';
            

        }
    }else{
        echo '
                alert("Only jpeg file...");history.back();
                ';
    }
}


function resize_image($file,$new_width,$new_height){
    if(file_exists($file)){
        $org_image = imagecreatefromjpeg($file);
        $org_width = imagesx($org_image);
        $org_height = imagesy($org_image);
        if($org_image){   
            $newimg = imagecreatetruecolor($new_width,$new_height);
            imagecopyresampled($newimg,$org_image,0,0,0,0,$new_width,$new_height,$org_width,$org_height);
            imagejpeg($newimg,$file,90);
        }

    }
}

PHP Login using Google Account

Hi guys,
here is the code How to login with google API

Learn How to make Login with Google Account using PHP. How to implement PHP Login using Google Account. How to Login with Google API using PHP. How to create a Google Login page in PHP. How to develop a Login System with Google OAuth using PHP.

require_once 'vendor/autoload.php';
//config.php

    
    $google_client = new Google_Client();
    $google_client-&gt;setClientId('');//Set the OAuth 2.0 Client ID
    $google_client-&gt;setClientSecret('');//Set the OAuth 2.0 Client Secret key
    $google_client-&gt;setRedirectUri('http://localhost/Login_System/index.php');//Set the OAuth 2.0 Redirect URI
    $google_client-&gt;addScope('email');
    $google_client-&gt;addScope('profile');
    session_start();
     
    //index.php

//Include Configuration File
include('config.php');

$login_button = '';

//This $_GET["code"] variable value received after user has login into their Google Account redirct to PHP script then this variable value has been received
if(isset($_GET["code"]))
{
 //It will Attempt to exchange a code for an valid authentication token.
 $token = $google_client-&gt;fetchAccessTokenWithAuthCode($_GET["code"]);

 //This condition will check there is any error occur during geting authentication token. If there is no any error occur then it will execute if block of code/
 if(!isset($token['error']))
 {
  //Set the access token used for requests
  $google_client-&gt;setAccessToken($token['access_token']);

  //Store "access_token" value in $_SESSION variable for future use.
  $_SESSION['access_token'] = $token['access_token'];

  //Create Object of Google Service OAuth 2 class
  $google_service = new Google_Service_Oauth2($google_client);

  //Get user profile data from google
  $data = $google_service-&gt;userinfo-&gt;get();

  //Below you can find Get profile data and store into $_SESSION variable
  if(!empty($data['given_name']))
  {
   $_SESSION['user_first_name'] = $data['given_name'];
  }

  if(!empty($data['family_name']))
  {
   $_SESSION['user_last_name'] = $data['family_name'];
  }

  if(!empty($data['email']))
  {
   $_SESSION['user_email_address'] = $data['email'];
  }

  if(!empty($data['gender']))
  {
   $_SESSION['user_gender'] = $data['gender'];
  }

  if(!empty($data['picture']))
  {
   $_SESSION['user_image'] = $data['picture'];
  }
 }
}

//This is for check user has login into system by using Google account, if User not login into the system then it will execute if a block of code and make code for display Login link for Login using Google account.
if(!isset($_SESSION['access_token']))
{
 //Create a URL to obtain user authorization
 $login_button = '<a>createAuthUrl().'"&gt;<img src="sign-in-with-google.png"></a>';
}
//logout.php

include('config.php');

//Reset OAuth access token
$google_client-&gt;revokeToken();

//Destroy entire session data.
session_destroy();

//redirect page to index.php
header('location:index.php');


//For Source Code
<a href="https://github.com/vinayakz/Task/tree/master/login_with_google">For Source Code</a>