CODE HELP

Some of the important most useful codes.

HTML


Bootstrap 3 skeleton (With Fontawesome)

<!DOCTYPE html>
<html lang="en">
<head>
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>PROJECT</title>
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="application-name" content="PROJECT">
	<meta name="description" content="">
	<meta name="application-url" content="">
	<link rel="shortcut icon" href="" type="image/x-icon">

	<!-- Styles -->
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
</head>
<body>

	<div class="container">
		<div class="row">
			<div class="col-md-6">
				
			</div>
		</div>
	</div>


	<!-- Scripts -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>
</html>

Bootstrap 4 Skeliton

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
  </body>
</html>

Material skeleton

<!DOCTYPE html>
<html>
<head>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>PROJECT</title>
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="application-name" content="PROJECT">
	<meta name="description" content="">
	<meta name="application-url" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
	<link rel="shortcut icon" href="" type="image/x-icon">
	
	<!--Import Google Icon Font-->
	<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
	<!--Import materialize.css-->
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" />

	<!--Let browser know website is optimized for mobile-->
</head>

<body>

	<!--JavaScript at end of body for optimized loading-->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>

Disable image drag option

 <img src="" ondragstart="return false;">

CSS


CSS Sprite Generator

https://responsive-css.us/

Multiple images use as a one image

CSS child selection

li:first-child {

}
li:nth-child(2) {

}
li:last-child {

}

CSS Media query

@media only screen and (max-width: 500px) {

}

@media only screen and (max-width: 600px) and (min-width: 400px)  {

}

Javascript


Script for after load data

$('#datatable').on('click', '.deleteitm', function(){

 });

Data table load data script / not work click when load data by ajax

Add file input preview

<input type="file" accept="image/*" onchange="loadFile(event)">
<img id="output"/>
<script>
  var loadFile = function(event) {
    var output = document.getElementById('output');
    output.src = URL.createObjectURL(event.target.files[0]);
  };
</script>

Input File preview

Export table as excel

<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
<iframe id="txtArea1" style="display:none"></iframe>

<script type="text/javascript">
function fnExcelReport(){
  var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
  var textRange; var j=0;
  tab = document.getElementById('headerTable'); // id of table

  for(j = 0 ; j < tab.rows.length ; j++){     
    tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
  }

  tab_text=tab_text+"</table>";
  tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
  tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
  tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

  var ua = window.navigator.userAgent;
  var msie = ua.indexOf("MSIE "); 

  if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
    txtArea1.document.open("txt/html","replace");
    txtArea1.document.write(tab_text);
    txtArea1.document.close();
    txtArea1.focus(); 
    sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
  }  
  else
    sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  
  return (sa);
}
</script>

Javascript Document Ready

(function() {

})();

Navbar li active

/*======= Active Nav ===============*/
var path = /[^/]*$/.exec(window.location.pathname)[0];
$(".nav a").each(function () {
  var $this = $(this);
  if($this.attr('href').indexOf(path) != -1){
    $this.closest('li').addClass('active');
  }
});

It will only work for extension show-able url.
ex: www.abc.com/about.php / www.abc.com/about.html

Get History of page browse

function checkHistory() {
  var history = localStorage.history;
  // console.log(history);
  var htmlContent = '';
  if (history != "" && history != null) {
    var insert = true;
    var sp = history.toString().split(",");
  
    if (insert) {
      sp.push(document.URL);
    }
    localStorage.history = sp.toString();
  } else {
    var stack = new Array();
    stack.push(document.URL);
    localStorage.history = stack.toString();
  }
  return history;
}
console.log(checkHistory());

It will show history of user visited pages

JavaScript Code Encrypt/hide

http://www.javascriptobfuscator.com/Javascript-Obfuscator.aspx

If Checkbox checked

$('#selectAll').change(function(event) {
  if ($(this).is(':checked')) {
     alert('checked');
  }else{

  }
});

JavaScript Encode Decode

console.log(btoa("Developing by Mamunur Rashid \n https://www.mamunr.com"));

console.log(atob("RGV2ZWxvcGluZyBieSBNYW11bnVyIFJhc2hpZCAKIGh0dHBzOi8vd3d3Lm1hbXVuci5jb20="));

jQuery Checkbox on change / If Checkbox checked

$(".checkbox").change(function() {
    if(this.checked) {
        //Do stuff
    }
});

Select Option by value

$('.category option[value=value]').attr('selected','selected');  //for  static value
$('.category option[value='+$category+']').attr('selected','selected'); //for dynamic value

jQuery Timeout / wait time

setTimeout(function(){

}, 3000);

Data Spay (Add class in nav when scrool)

data-spy="scroll" data-target=".sidebar" data-offset="200"

Add the code in the body tag, make sure the class you giving it have 'nav' child class

Smooth Scrolling

$(document).ready(function(){
	$('.leftBar a[href^="#"]').on('click',function (e) {
	  e.preventDefault();

	  var target = this.hash;
	  var $target = $(target);

	  $('html, body').stop().animate({
	      'scrollTop': $target.offset().top
	  }, 900, 'swing', function () {
	      window.location.hash = target;
	  });
	});
});

Owl Carousel

<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/owl.carousel.min.js"></script>
<script>
  $(".owl-carousel").owlCarousel(
    {
      items: 2,
      itemsDesktop : [1000,2], // 2 items between 1000px and 901px
      itemsDesktopSmall : [900,2], // betweem 900px and 601px
      itemsTablet: [700,2], // 2 items between 600 and 480
      itemsMobile : [479,1] , // 1 item between 479 and 0
      navigation: true,
      lazyLoad: true,
      pagination: false,
      scrollPerPage : true,
      autoplay:true,
      loop:true,
      autoplay:true,
      autoplayTimeout:1000,
      autoplayHoverPause:true
    }
  );
</script>

Ajax

$.ajax({
  url: "script.php",
  method: "POST",
  data: { id : menuId },
  dataType: "html"
}).done(function( msg ) {
  $( "#log" ).html( msg );
}).fail(function( jqXHR, textStatus ) {
  alert( "Request failed: " + textStatus );
});

Wrap the scripts for WordPress

(function($) {
	
})( jQuery );

PHP


Database Connection (OOP)

class DBConnection extends PDO {
	public function __construct(){
		$host='localhost';
		$dbname='DBName';
		$user='root';
		$pass='';

  parent::__construct("mysql:host=$host;dbname=$dbname", $user, $pass);
  $this->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
 }
}

$conn = new DBConnection();

Inseart Data

$stmt = $conn->prepare("INSERT INTO `mytable`(`name`, `roll`, `class`) VALUES (:name,:roll,:class)");
$stmt->execute(array(
 ':name' 		=> $name,
 ':email' 	=> $email,
 ':class' 	=> $class
));

Select/Get Data from database

$stmt = $conn->prepare("SELECT * FROM user");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
foreach($result as $row){
	var_dump($row);
	echo $row['name'];
}

Select BETWEEN Date

"SELECT * FROM ct_expense WHERE (exDate BETWEEN '$dateA' AND '$dateB')"

Get Location using IP / IP to Location

function get_client_ip() {
      $ipaddress = '';
      if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
      else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
      else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
      else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
      else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
      else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
      else
        $ipaddress = 'UNKNOWN';
      return $ipaddress;
    }
		$PublicIP = get_client_ip(); 
		$ch = curl_init("https://api.ip2location.com/v2/?ip=$PublicIP&key=demo&package=WS3&addon=city");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS);
		$response = curl_exec($ch);
		curl_close($ch);

Delete Database Data

$stmt = $conn->prepare("DELETE FROM `user` WHERE id = :id");
$stmt->execute(array(':id' 	=> 1));

Update Database Data

$stmt = $conn->prepare("UPDATE `user` SET `name`=:name,`email`=:email WHERE id = :id");
$stmt->execute(array(
 ':name' 		=> $name,
 ':email' 		=> $email,
 ':id' 	=> 1
));

Group/Join Data select from database

$stmt = $conn->prepare("SELECT cat_tbl_id,pwc_id,page_url,name FROM page_with_cat 
	LEFT JOIN category ON page_with_cat.cat_tbl_id = category.cat_id");
$stmt->execute();
$assignCat = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

PHP curl / PHP get data (json) from url

$post = [
  'key' => '26e7458dc56ab28',
  'act' => 'balance'
];

$ch = curl_init('http://portal.smsinbd.com/api');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
curl_close($ch);

Flikar API

Javascript
==============
https://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=47ac226593bc6e8016de6c10a31a920b&[email protected]&format=json

//Output  
https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg




PHP
================
<?php
function resize_image($file, $w, $h, $crop=FALSE) {
  list($width, $height) = getimagesize($file);
  $r = $width / $height;
  if ($crop) {
    if ($width > $height) {
      $width = ceil($width-($width*abs($r-$w/$h)));
    } else {
      $height = ceil($height-($height*abs($r-$w/$h)));
    }
    $newwidth = $w;
    $newheight = $h;
  } else {
    if ($w/$h > $r) {
      $newwidth = $h*$r;
      $newheight = $h;
    } else {
      $newheight = $w/$r;
      $newwidth = $w;
    }
  }
  $src = imagecreatefromjpeg($file);
  $dst = imagecreatetruecolor($newwidth, $newheight);
  imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

  return $dst;
}



$json = file_get_contents('https://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=47ac226593bc6e8016de6c10a31a920b&[email protected]&format=json');
$json = str_replace("jsonFlickrApi(", "",$json);
$json = str_replace(")", "",$json);

$obj =  json_decode($json, TRUE);


foreach ($obj['photos']['photo'] as $data) {

	// The file
	$filename = "https://farm".$data['farm'].".staticflickr.com/".$data['server']."/".$data['id']."_".$data['secret'].".jpg";

	$ss = "../demo-resized".$data['id'].".jpg";
	$img = resize_image($filename, 120, 120);
	imagejpeg($img, $ss);
	?>

	<img src="<?= $ss ?>"/> <?php

}
?>

Add Subscriber in mailchamp list

$fname = 'Max';
$lname = 'Hount';
$email = "[email protected]";
if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false){
 // MailChimp API credentials
 $apiKey = 'YourApiKey';
 $listID = 'ListIdWhereYouWantToAdd';

 // MailChimp API URL
 $memberID = md5(strtolower($email));
 $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
 $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;

 // member information
 $json = json_encode([
  'email_address' => $email,
  'status'        => 'subscribed',
  'merge_fields'  => [
   'FNAME'  => $fname,
   'LNAME'  => $lname
  ]
 ]);

 // send a HTTP POST request with curl
 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
 curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
 $result = curl_exec($ch);
 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 curl_close($ch);

 // store the status message based on response code
 if ($httpCode == 200) {
     $_SESSION['msg'] = 'You have successfully subscribed to CodexWorld.';
 } else {
  switch ($httpCode) {
   case 214:
    $msg = 'You are already subscribed.';
    break;
   default:
    $msg = 'Some problem occurred, please try again.';
    break;
  }
  $_SESSION['msg'] = $msg;
 }
}else{
 $_SESSION['msg'] = 'Please enter valid email address.';
}

Get API key from "https://usX.admin.mailchimp.com/account/" > Extras > API Keys Get List ID from "https://usX.admin.mailchimp.com/lists/" > (Open A list) > Setting > List name and campaign defaults

SHow Character limit by keeping last word

if(strlen($string) > $limit) {
  $text = preg_replace("/^(.{1,$limit})(\s.*|$)/s", '\\1...', $string);
}else{
  $text = $string;
}
echo $text;

Replace word/sting

str_replace('Old_Word', 'New_Word', $string);

HTML entiti encode & Line breaks/New line

htmlentities($_POST['title']);
htmlspecialchars_decode($string);
htmlspecialchars($string, ENT_QUOTES);
nl2br(htmlentities($_POST['title']));

htmlentities() will encode (<,>,",' etc) the string, nl2br() will keep the line break of string .

WordPress


Bacis Code

<meta charset="<?php bloginfo('charset') ?>">
<meta name="description" content="<?php bloginfo('description') ?>">

wp_head();     //Add before ending head tag
wp_footer();   //Add before ending body tag
get_header();  //For Call header.php
get_footer();  //For Call footer.php
the_title();
the_content()
the_post_thumbnail();
the_excerpt()
get_the_date( 'jS M Y' );
the_content_rss()
the_ID()
comments_number( 'no responses', 'one response', '% responses' );
get_template_directory_uri() //Diractory path

load_theme_textdomain('text-domain-name', get_template_directory_uri().'/language'); //Text Domain

Wp Media Uploader

<div class="mediaUploadHolder">
  <button type="button" class="mediaUploader btn btn-info">Upload
  </button>
  <input class="hidden teacherImg" type="text" name="stdImg" value="<?= $edit->stdImg ?>">
</div>

var media_uploader = '';
$('.mediaUploader').click(function(event) {
  var $this = $(this);
  media_uploader = wp.media({
    frame:    "post",
    state:    "insert",
    multiple: false
  });

  media_uploader.on("insert", function(){
    var json = media_uploader.state().get("selection").first().toJSON();

    var image_url = json.url;
    var image_caption = json.caption;
    var image_title = json.title;
    $this.closest('.mediaUploadHolder').find('span').html("<img height='40' src='"+image_url+"'>");
    $this.closest('.mediaUploadHolder').find('.teacherImg').val(image_url);
  });

  media_uploader.open();
});

//in function
wp_enqueue_media();

WP Create Admin User (Admn Account)

function wpb_admin_account(){
  $user = 'Username';
  $pass = 'Password';
  $email = '[email protected]';
  if ( !username_exists( $user )  && !email_exists( $email ) ) {
    $user_id = wp_create_user( $user, $pass, $email );
    $user = new WP_User( $user_id );
    $user->set_role( 'administrator' );
  }
}
add_action('init','wpb_admin_account');

WP Select Data

$fivesdrafts = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'draft'");

foreach ( $fivesdrafts as $fivesdraft ){
	echo $fivesdraft->post_title;
}

Widget

// Register and load the widget
function wpb_load_widget() {
    register_widget( 'wpb_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );
 
// Creating the widget 
class wpb_widget extends WP_Widget {
 
function __construct() {
parent::__construct(
 
// Base ID of your widget
'wpb_widget', 
 
// Widget name will appear in UI
__('WPBeginner Widget', 'wpb_widget_domain'), 
 
// Widget description
array( 'description' => __( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), ) 
);
}
 
// Creating widget front-end
 
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
 
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
 
// This is where you run the code and display the output
echo __( 'Hello, World!', 'wpb_widget_domain' );
echo $args['after_widget'];
}
         
// Widget Backend 
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'wpb_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php 
}
     
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
}

Add custom post/meta data in admin post list table

add_filter( 'manage_ico_list_posts_columns', 'set_custom_edit_ico_list_columns' );
function set_custom_edit_ico_list_columns($columns) {
  unset( $columns['date'] );
  $columns['ico_start_date'] = __( 'Stat Date', 'ico_textdomain' );
  $columns['ico_end_date']   = __( 'End Date', 'ico_textdomain' );
  $columns['ico_category']   = __( 'Ico Category', 'ico_textdomain' );

  return $columns;
}

add_action( 'manage_ico_list_posts_custom_column' , 'custom_ico_list_column', 10, 2 );
function custom_ico_list_column( $column, $post_id ) {
  $startDate = get_post_meta( $post_id , 'ico_start_date' , true );
  $endDate   = get_post_meta( $post_id , 'ico_end_date' , true );
  switch ( $column ) {
    case 'ico_start_date' :
      echo $startDate;
      break;

    case 'ico_end_date' :
      echo $endDate; 
      break;

    case 'ico_category' :
      if($endDate <= date("Y-m-d")){
        echo "End";
      }
      elseif(date("Y-m-d") >= $startDate){
        echo "Active";
      }else{
        echo "Upcoming";
      }
      break;

  }
}

WP Boostrap Slider

$the_query = new WP_Query(array(
  'post_type' => 'PostID',
  'posts_per_page' => 1
));
while ( $the_query->have_posts() ) :
  $the_query->the_post();
  ?>
  <div class="item active"><?php the_title();?></div>
  <?php
endwhile;

wp_reset_postdata();

$the_query = new WP_Query(array(
  'post_type' => 'PostID',
  'offset' => 1
));
while ( $the_query->have_posts() ) :
  $the_query->the_post();
  ?>
    <div class="item><?php the_title();?></div>
  <?php
endwhile;
wp_reset_postdata();

WP Delete Data

$wpdb->delete(
	'products',
	array(
		'product_id' => $id
	)
);

WP Update Data

$update = $wpdb->update(
	'TableName',
	array(
		'ColumnName'			=>	 'Data',
		'product_title'			=>	 $edit_product_title,
	),
	array( 'product_id' => $id ) //Where will go
);

WP Insert Data

$insert = $wpdb->insert(
	'TableName',
	array(
		'ColumnName' 			=> 'Data',
		'product_title' 		=> $product_title,
	)
);

MetaBox

class ico_list {

 public function __construct() {
  add_action( 'add_meta_boxes', array( $this, 'max_add_meta_box' ) );
  add_action( 'save_post',      array( $this, 'save'         ) );
 }

 public function max_add_meta_box( $post_type ) {
  // Assign metabot to post
  $post_types = array( 'post_id_1', 'post_id_2' );

  if ( in_array( $post_type, $post_types ) ) {
   add_meta_box(
    'metaboxID',
    __( 'Metabox Title', 'textDomain' ),
    array( $this, 'render_ico_meta_content' ),
    $post_type,
    'advanced',
    'high'
   );
  }
 }

 public function save( $post_id ) {
      
  // Check if our nonce is set.
  if( !isset( $_POST['myplugin_inner_custom_box_nonce']) ){ return $post_id; }

  $nonce = $_POST['myplugin_inner_custom_box_nonce'];

  // Verify that the nonce is valid.
  if(!wp_verify_nonce( $nonce, 'myplugin_inner_custom_box')){ return $post_id; }

		if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return $post_id; }

  // Check the user's permissions.
   if ( 'page' == $_POST['post_type'] ) {
    if(!current_user_can('edit_page', $post_id )){ return $post_id; }
    } else {
     if(! current_user_can( 'edit_post', $post_id )){ return $post_id; }
    }

				// Sanitize the user input.
    $website = sanitize_text_field( $_POST['website'] );
    $ico_topIco = sanitize_text_field( $_POST['ico_topIco'] );

    // Update the meta field.
    update_post_meta( $post_id, 'website', $website );
    update_post_meta( $post_id, 'ico_topIco', $ico_topIco );
 }


 public function render_ico_meta_content( $post ) {

  wp_nonce_field('myplugin_inner_custom_box', 'myplugin_inner_custom_box_nonce');

  // Use get_post_meta to retrieve an existing value from the database.
  $website = get_post_meta( $post->ID, 'website', true );
  $ico_topIco = get_post_meta( $post->ID, 'ico_topIco', true );

  // Display the form, using the current value.
  ?>

   <table class="widefat">
     <tr>
       <td>
         <label for="website">
           <b>
             <?php _e( 'Website URL', 'textDomain' ); ?> :
           </b>
         </label>
       </td>
       <td colspan="3">
         <input type="url" id="website" name="website" value="<?= $website; ?>"  />
       </td>
       <td>
         <label for="ico_topIco">
           <b>
             <?php _e( 'Top/Featured', 'textDomain' ); ?> :
           </b>
         </label>
       </td>
       <td>
         <label>
           <input type="radio" id="ico_topIco" name="ico_topIco" value="1" <?= $ico_topIco == 1 ? 'checked' : "" ; ?> />Yes
         </label>
         <label>
           <input type="radio" id="ico_topIco" name="ico_topIco" value="2"  <?= $ico_topIco != 1 ? 'checked' : "" ; ?> />No
         </label>
       </td>
     </tr>

   </table>

  <?php
 }
}

function ico_call_twice() { new ico_list(); }

if ( is_admin() ) {
  add_action( 'load-post.php',     'ico_call_twice' );
  add_action( 'load-post-new.php', 'ico_call_twice' );
}

Change Post Placeholder

function wpb_change_title_text( $title ){
  $screen = get_current_screen();
  if  ( 'post ID' == $screen->post_type ) {
    $title = 'Plaseholder Text';
  }
  return $title;
}

Register Custom Post

function create_post_type() {
	register_post_type( 'custom_post_1',
		array(
			'labels'           => array(
				'name'          => __( 'Custom Post 1' ),
				'singular_name' => __( 'Post' )
			),
			'public'       => true,
			'has_archive'  => true,
   'menu_icon'   => 'dashicons-list-view',
'supports' => array('title','author','thumbnail','excerpt','comments')
  )
	);

 register_post_type( 'custom_post_2',
  array(
   'labels'        => array(
	   'name'          => __( 'Custom Post 2' ),
	   'singular_name' => __( 'Post' )
	  ),
  	'public'      => true,
   'has_archive' => true,
   'supports'    => array('title', 'editor', 'thumbnail'),
   'menu_icon'   => 'dashicons-exerpt-view'
  )
 );
 add_image_size( 'ico_icon_image', 70, 70, true);
}
add_action( 'init', 'create_post_type' );

Admin Ajax

//============ In function.php add ajax
function mamunursScripts() {
 wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ) . '/js/custom.js', array('jquery') );
 wp_localize_script( 'ajax-script', 'majaxObj', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'mamunursScripts');

//============ Function that will trigger by the ajax (Add in function.php)
add_action( 'wp_ajax_ajaxActionGet', 'ajaxActionGet' ); //only work for logedin user
add_action( 'wp_ajax_nopriv_ajaxActionGet', 'ajaxActionGet' ); //for logout user
function ajaxActionGet() {

 global $wpdb;

 wp_die();
}

//============ Javascript for Admin ajax  (Add the code in custom.js)
var data = {
 'action': 'ajaxActionGet',  //the function name will trigger by the ajax
 'yourData': "YourValue",
};
jQuery.post(majaxObj.ajax_url, data, function(response) {
 console.log(response);  
});

If you have a enque script function then just add only the body in your function.
Don't forget about data 'action' it will call the function from function.php

Add CSS & JS

function mamunursScripts() {

 wp_enqueue_style( 'bootstrap', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css' );
 wp_enqueue_style( 'daterangepicker', plugin_dir_url( __FILE__ ).'css/style.css' );

 wp_enqueue_script( 'jquery', "https://code.jquery.com/jquery-2.2.4.min.js" );
 wp_enqueue_script( 'popper', plugin_dir_url( __FILE__ ). 'js/custom.js' );

}
add_action('wp_enqueue_scripts', 'mamunursScripts');

WP Nav menu

//Register Menu
register_nav_menu('main-menu',__('Main Menu','text-domain-name'));  

//Show Menu
<ul class="nav navbar-nav">
 <?php
	 wp_nav_menu(array(
	    'theme_location' => 'main-menu',
	    'menu_class'=> 'nav navbar-nav navbar-right'
	 ));
	?>
</ul>

WP Redux


Add Redux

require_once('redux/ReduxCore/framework.php');
require_once('redux/sample/sample-config.php');

Add those 2 line in function.php.
Download Redux from : https://drive.google.com/open?id=1_h94GGcMk-xKcHbzsd_7ToivXkc3Y5_Z

Redux Show Data (Redux Output)

//First Globalize Tha Variable(global $opt_name;)
echo $opt_name['portfolio_heading_text'];
echo $opt_name['info_top_bg_img']['url'];

/* Slides Output */
if(is_array($opt_name['about_item'])){
	foreach($opt_name['about_item'] as $about){ ?>

		<i class="fa  media-object"></i>
		<h4 class="media-heading"><?php echo $about['title']; ?></h4>
		<p><?php echo $about['description']; ?></p>

		<?php
	}
}

Redux Section Making

Redux::setSection($opt_name,array(
	'id'			=> 'service_option',
	'title'		=> __('Service Section','text-domain'),
	'icon'		=> 'el el-star',
	'fields'	=>array(
		array(
			'id'		=> 'service_heading_text',
			'title'	=> __('Heading Text','text-domain'),
			'desc'	=> __('You can Change Heading From here.','text-domain'),
			'type'	=> 'text',
			'default'=> 'Our Services'
		),
		array(
			'id'		=> 'portfolio_item_'.$pro.'_desc',
			'title'	=> __('Description','text-domain'),
			'url'		=> true,
			'desc'	=> __('Description of this Project.','text-domain'),
			'type'	=> 'editor'
		),
		array(
			'id'		=> 'portfolio_item_'.$pro.'_desc',
			'title'	=> __('Description','text-domain'),
			'url'		=> true,
			'desc'	=> __('Description of this Project.','text-domain'),
			'type'	=> 'media',
				'url' 	=> true,
			'default'=> array(
				'url' 	=> get_template_directory_uri().'/derectory'
			)
		),
		array(
			'id'		=> 'service_item',
			'title'	=> __('Service Item','text-domain'),
			'desc'	=> __('You can Add/Remove Service Item From here.','text-domain'),
			'type'	=> 'slides',
			'show' => array(
                            'title' => true,
                            'description' => true,
                            'url' => false              // <<========= Disable fild 
                        ),
			'placeholder' => array(
				'title' => 'Service Item Title',
				'url' => 'Icon Class ex:fa-home'
			),
			'content_title' => __('Service','sigtuna')  // Change Slider Title
		)
	)
));

MySql


MySql Querys

SELECT ct_studentinfo.infoid, (SELECT COUNT(`spStdID`) FROM `ct_studentPoint` WHERE `spStdID` = ct_studentinfo.infoStdid) as toatl FROM `ct_studentinfo` HAVING toatl > 0

Update by shorting row number

UPDATE 
ct_cgpa TBL1 
INNER JOIN 
(
    SELECT cgpaid,
        @rowNumber := @rowNumber + 1 AS rowNum
    FROM ct_cgpa , (SELECT @rowNumber := 0) var
    WHERE `cgpaClass` = 44 AND `cgpaYear` = 2019
    ORDER BY `cgpaPoint` DESC
) AS TBL2
ON TBL1.cgpaid = TBL2.cgpaid
SET TBL1.cgpaPosition = TBL2.rowNum;

MYSQL Update Multiple Row

UPDATE settings SET `svalue` = CASE
 WHEN (smeta = 'serviceCharge') THEN '$serviceCharge' 
 WHEN (smeta = 'servCrgType') THEN '$servCrgType' END 
WHERE smeta = 'serviceCharge' OR smeta = 'servCrgType'

MYSQL Update Replace string

UPDATE MyTable
SET StringColumn = REPLACE (StringColumn, 'SearchForThis', 'ReplaceWithThis')
WHERE SomeOtherColumn LIKE '%PATTERN%'

Calculate And order by SUM

SELECT 
  `spStdID`,
  cast(sum((`spPoint`/100)*cgpaPercent) as decimal(12,2)) as spoint,
  sum(spTotalMark) as totalmark 
FROM `ct_studentPoint`
LEFT JOIN ct_exam ON ct_exam.examid = ct_studentPoint.spExam 
WHERE `spClass` = 49 AND `spYear` = 2019 GROUP BY `spStdID`
ORDER BY spoint DESC

Laravel


Laravel

#################################
  Laravel Pre Instalation
#################################
  1. Install xammp/wamp (No need to run, Just for php and mysql)
  2. Install Composer
  3. Install Git (Not necessary, But Recommended)

#################################
  Laravel Instalation
#################################
  1. Create a directory whare you want to install/download the Laravel (ex: max_project)
  2. Open GitBush in perent directory of your folder ()
  3. Run the command in GitBush for download laravel
    composer create-project --prefer-dist laravel/laravel max_project
  4. Run the command in GitBush for go to the project directory (max_project)
    cd max_project
  5. Run the command in GitBush for start the project
    php artisan serve

#################################
  File Stracture
#################################
Route Files
  app/Http/routes.php
Conteoller Files
  app/Http/Conteollers/Conteoller.php
View Files
  resources/views
Database Connection File
  .env

#################################
  Setting up other things
#################################
App URL Setting
  config/app.php  => 'url'

############################
Move project
############################
1.composer install
2.npm install
3.cp .env.example .env
4.php artisan key:generate  
5.php artisan cache:clear
6.php artisan migrate

GitHub


GitHub

Login
------------
git config --global user.email "[email protected]"
git config --global user.name "rfmamun"

New Push into git
--------------------------
git init
git config core.autocrlf true
git add .
git commit -m "First commit"
git remote add origin remote repository URL
git remote -v
git push origin master

Get Data From GIT
----------------------
git clone (url)

Codignator


Codignator File

https://mamunr.com/help/file/cd.rar

Codignator File With Template