Insert and Display form Data Using JOIN in PHP

Create table ‘category’


CREATE TABLE category
(
c_id int AUTO_INCREMENT,
c_name varchar(255),
b_name varchar(255),
PRIMARY KEY (c_id)
);

Create table ‘product’


CREATE TABLE product
(
p_id INT(11) AUTO_INCREMENT,
c_id INT(11),    
p_name varchar(255),
p_price INT(11),
p_color varchar(255),
PRIMARY KEY (p_id)
);

Create “category.php”


<?PHP include 'connect.php'; ?>

<form method="post">
  Product Category
  <input type="text" name="category">
  </br>
  </br>
  Brand Name
  <input type="text" name="bname">
  </br>
  </br>
  <input type="submit" name="add_category" value="Add Category" />
</form>
<?php 
if(isset($_POST['add_category'])){
	$product_category = $_POST['category'];
	$brand_name = $_POST['bname'];
	$query2 = "INSERT INTO `category` (`c_name`,`b_name`) VALUES ('".$product_category."','".$brand_name."')";
	$result2 = mysql_query($query2) or die(mysql_error());
}

?>

Create “product.php”


<?php include 'connect.php'; ?>

<form method="post">
  Category Name
  <?php 
  $category = "SELECT c_name, c_id FROM category";
	$cat_result = mysql_query($category);
	?>
  <select name="category">
    <?php
	while($cat_row = mysql_fetch_array($cat_result)) { ?>
    <option value="<?php echo $cat_row['c_id']; ?>"><?php echo $cat_row['c_name']; ?></option>
    <?php }	?>
  </select>
  </br>
  </br>
  Product Name
  <input type="text" name="pname">
  </br>
  </br>
  Product Price
  <input type="text" name="price">
  </br>
  </br>
  Product Color
  <input type="checkbox" value="red" name="color[]" />
  Red,
  <input type="checkbox" value="blue" name="color[]" />
  Blue,
  <input type="checkbox" value="black" name="color[]" />
  Black</br>
  </br>
  <input type="submit" name="add_product" value="Add Product" />
</form>
<?php
if(isset($_POST['add_product'])){
	$c_id = $_POST['category'];
	$product_name = $_POST['pname'];
	$product_price = $_POST['price'];
	$product_color = implode(', ',$_POST['color']);
	
	$query1 = "INSERT INTO `product` (`c_id`,`p_name`,p_price,p_color) VALUES ('".$c_id."','".$product_name."','".$product_price."','".$product_color."')";
	$result1 = mysql_query($query1) or die(mysql_error());
}

?>

Create “result.php”


<?php
include 'connect.php';
$query = "SELECT product.*, category.* 
		  FROM product 
		  JOIN category 
		  ON product.c_id=category.c_id";	  

$result = mysql_query($query);

?>

<table border="1">
<tr>
  <td>Product ID</td>
  <td>Product Name</td>
  <td>Product Price</td>
  <td>Product Color</td>
  <td>Product Category ID</td>
  <td>Product Category </td>
  <td>Brand Name</td>
</tr>
<?php while($row = mysql_fetch_array($result)) { ?>
<tr>
  <td><?php echo $row['p_id']; ?></td>
  <td><?php echo $row['p_name']; ?></td>
  <td><?php echo $row['p_price']; ?></td>
  <td><?php echo $row['p_color']; ?></td>
  <td><?php echo $row['c_id']; ?></td>
  <td><?php echo $row['c_name']; ?></td>
  <td><?php echo $row['b_name']; ?></td>
</tr>
<?php } ?>

Create “connect.php”


<?php

$dbname = 'php';
$dbuser = 'root';
$dbpass = '';
$dbhost = 'localhost';

$con = mysql_connect($dbhost,$dbuser,$dbpass);
$db =  mysql_select_db($dbname, $con) or die(mysql_error());
 
?>

Insert Update Delete Search (Radio, Checkbox, Imge) with Pagination in PHP

Create database

CREATE DATABASE IF NOT EXISTS `test` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;

Create table

CREATE TABLE IF NOT EXISTS `tbl1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(11) NOT NULL,
  `number` varchar(11) NOT NULL,
  `pass` varchar(11) NOT NULL,
  `cpass` varchar(11) NOT NULL,
  `city` varchar(11) NOT NULL,
  `gender` varchar(11) NOT NULL,
  `job` varchar(50) NOT NULL,
  `image` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=132 ;

Create index.php

<form name="f1" method="post" enctype="multipart/form-data">
  name
  <input type="text" name="name" id="name">
  <br>
  Number
  <input type="text" name="number" id="number">
  <br>
  password
  <input type="text" name="pass" id="pass">
  <br>
  conform pass
  <input type="text" name="cpass" id="cpass">
  <br>
  city
  <select name="city" id="city">
    <option></option>
    <option value="junagadh">junagaadh</option>
    <option value="keshod">Keshod</option>
  </select>
  <br>
  Gender
  <input type="radio" name="gender" value="male" id="gender" />
  Male
  <input type="radio" value="female" name="gender" id="gender" />
  Female<br>
  job
  <input type="checkbox" name="job[]" value="developer" id="developer" />
  Developer
  <input type="checkbox" name="job[]" value="designer" id="designer" />
  Designer<br>
  <input type="file" name="image" id="image" />
  <input type="submit" name="insert" value="insert">
  <br>
</form>
<?php

$cn = mysql_connect("localhost","root","");
$db = mysql_select_db("test",$cn);

if(isset($_POST['insert']))
{
	$name = $_POST["name"];
	$number = $_POST["number"];
	$pass = $_POST["pass"];
	$cpass = $_POST["cpass"];
	$city = $_POST["city"];
	@$gender = $_POST["gender"];
	@$job = implode(",",$_POST["job"]);
	
	$image = $_FILES['image']['name'];
	$define_name = "image_".microtime().".jpg";
	move_uploaded_file($_FILES['image']['tmp_name'],"upload/".$define_name);
	
	$q = "INSERT INTo `tbl1` (`name`, `number`, `pass`, `cpass`, `city`, `gender`, `job`, `image`)
		  VALUES ('".$name."', '".$number."', '".$pass."', '".$cpass."', '".$city."', '".$gender."', '".$job."', '".$define_name."')";

	$r = mysql_query($q);
}
echo '<a href="display.php">Display Records</a>';
?>

Create display.php


<form method="post" action="search_all.php">
  Search
  <input type="text" name="search_all" />
  <input type="submit" name="submit" value="submit" />
</form>
<?php
	$cn = mysql_connect("localhost","root","");
	$db = mysql_select_db("test",$cn);
	
	$q = "SELECT * FROM `tbl1`";
	$r = mysql_query($q);
	 
		$row2 = mysql_num_rows($r);
		$limit = 2;
		$page_devide = ceil($row2/$limit);
		if(!isset($_GET['page']))
		{
			header("location:display.php?page=1"); 
		}
		else
		{
			$page = $_GET['page'];
		}
			$start = ($page-1)*$limit;
			$q2 = "select * from tbl1 limit $start,$limit";
			$r2 = mysql_query($q2);
	?>
<table border="1">
  <tr>
    <td>name</td>
    <td>number</td>
    <td>pass</td>
    <td>cpass</td>
    <td>city</td>
    <td>gender</td>
    <td>job</td>
    <td>Image</td>
    <td>Edit</td>
    <td>Delete</td>
  </tr>
  <?php while($row = mysql_fetch_array($r2)) { ?>
  <tr>
    <td><?php echo $row['name']; ?></td>
    <td><?php echo $row['number']; ?></td>
    <td><?php echo $row['pass']; ?></td>
    <td><?php echo $row['cpass']; ?></td>
    <td><?php echo $row['city']; ?></td>
    <td><?php echo $row['gender']; ?></td>
    <td><?php echo $row['job']; ?></td>
    <td><img src="upload/<?php echo $row['image']; ?>" width="50" height="50"></td>
    <td><a href="edit.php?hid=<?php echo $row['id']; ?>">Edit</a></td>
    <td><a href="delete.php?hid=<?php echo $row['id']; ?>&image=<?php echo $row['image']; ?>">Delete</a></td>
  </tr>
  <?php } ?>
  <?php 
	
		for($i=1;$i<=$page_devide;$i++)
		{
			?>
  <a href="display.php?page=<?php echo $i; ?>"><?php echo $i;?></a>
  <?php	
		}
	?>
</table>

Create delete.php

<?php
$cn = mysql_connect("localhost","root","");
$db = mysql_select_db("test",$cn);
$id = $_REQUEST['hid'];
$image = $_REQUEST['image'];
$q="DELETE FROM tbl1 WHERE id=".$id; 
$r=mysql_query($q) or die(mysql_query());
unlink("upload/".$image);
header("location:display.php");
?>

Create edit.php

<?php

$cn = mysql_connect("localhost","root","");
$db = mysql_select_db("test",$cn);

if(isset($_REQUEST['hid']))
{
	$id = $_REQUEST['hid'];
	$q = "SELECT * FROM `tbl1` WHERE `id` = '".$id."'";
	$r = mysql_query($q);
}
	while($row = mysql_fetch_array($r))
	{
		$id = $row['id'];
		$name = $row['name'];
		$number = $row['number'];
		$pass = $row['pass'];
		$cpass = $row['cpass'];
		$city = $row['city'];
		$gender = $row['gender'];
		$job = explode(",",$row['job']);
		$image = $row['image']; 
	}
?>

<form name="f1" method="post" enctype="multipart/form-data">
  <input type="hidden" name="id" value="<?php echo $id; ?>">
  name
  <input type="text" name="name" id="name" value="<?php echo $name;  ?>">
  <br>
  Number
  <input type="text" name="number" id="number" value="<?php echo $number;  ?>">
  <br>
  password
  <input type="text" name="pass" id="pass" value="<?php echo $pass;  ?>">
  <br>
  conform pass
  <input type="text" name="cpass" id="cpass" value="<?php echo $cpass;  ?>">
  <br>
  city
  <select name="city" id="city">
    <option></option>
    <option value="junagadh" <?php if($city == "junagadh") { ?> selected="selected">
    <?php } ?>
    junagaadh</option>
    <option value="keshod" <?php if($city == "keshod"){ ?> selected="selected" <?php } ?>>Keshod</option>
  </select>
  <br>
  Gender
  <input type="radio" name="gender" value="male" id="gender" <?php if($gender == "male"){ ?> checked="checked" <?php } ?> />
  Male
  <input type="radio" value="female" name="gender" id="gender" <?php if($gender == "female") { ?> checked="checked" <?php } ?> />
  Female<br>
  job
  <input type="checkbox" name="job[]" value="developer" id="developer" <?php if(in_array("developer",$job)){ ?> checked="checked" <?php } ?> />
  Developer
  <input type="checkbox" name="job[]" value="designer" id="designer" <?php if(in_array("designer",$job)){ ?> checked="checked" <?php } ?> />
  Designer<br>
  <input type="file" name="image" id="image" />
  <img src="upload/<?php echo $image; ?>" width="50" height="50"><br>
  <input type="submit" name="edit" value="edit">
  <br>
  <input type="hidden" name="old_image" value="<?php echo $image; ?>" />
</form>
<?php

if(isset($_POST['edit']))
{
		$id = $_POST['id'];
		$name = $_POST['name'];
		$number = $_POST['number'];
		$pass = $_POST['pass'];
		$cpass = $_POST['cpass'];
		$city = $_POST['city'];
		@$gender = $_POST['gender'];
		@$job = implode(",",($_POST['job']));
		
		$image = $_FILES['image']['name'];
		$define_name = "image_".microtime().".jpg";
		
		$old_image = $_REQUEST['old_image'];
		unlink("upload/".$old_image);
		
		move_uploaded_file($_FILES['image']['tmp_name'],"upload/".$define_name);
		
		$q = "UPDATE `tbl1` SET `name` = '".$name."', `number` = '".$number."', `pass` = '".$pass."',   	
			 `cpass` = '".$cpass."', `city` = '".$city."', `gender` = '".$gender."', `job` = '".$job."',
			 `image` = '".$define_name."' WHERE `id` = '".$id."'";
			 
		
		$r = mysql_query($q)or die(mysql_query());

		header("location:display.php");
}

?>

Create search_all.php

<?php

$cn = mysql_connect("localhost","root","");
$db = mysql_select_db("test",$cn);

$q = "SELECT * 
FROM  `tbl1` 
WHERE  `name` LIKE  '%".$_POST['search_all']."%'
OR  `number` LIKE  '%".$_POST['search_all']."%'
OR  `pass` LIKE  '%".$_POST['search_all']."%'
OR  `cpass` LIKE  '%".$_POST['search_all']."%'
OR  `city` LIKE  '%".$_POST['search_all']."%'
OR  `gender` LIKE  '%".$_POST['search_all']."%'
OR  `job` LIKE  '%".$_POST['search_all']."%'
OR  `image` LIKE  '%".$_POST['search_all']."%'";

$r = mysql_query($q);
?>

<table border="1">
  <tr>
    <td>name</td>
    <td>number</td>
    <td>pass</td>
    <td>cpass</td>
    <td>city</td>
    <td>gender</td>
    <td>job</td>
    <td>Image</td>
    <td>Edit</td>
    <td>Delete</td>
  </tr>
  <?php while($row = mysql_fetch_array($r)) { ?>
  <tr>
    <td><?php echo $row['name']; ?></td>
    <td><?php echo $row['number']; ?></td>
    <td><?php echo $row['pass']; ?></td>
    <td><?php echo $row['cpass']; ?></td>
    <td><?php echo $row['city']; ?></td>
    <td><?php echo $row['gender']; ?></td>
    <td><?php echo $row['job']; ?></td>
    <td><img src="upload/<?php echo $row['image']; ?>" width="50" height="50"></td>
    <td><a href="edit.php?hid=<?php echo $row['id']; ?>">Edit</a></td>
    <td><a href="delete.php?hid=<?php echo $row['id']; ?>&image=<?php echo $row['image']; ?>">Delete</a></td>
  </tr>
  <?php } ?>
</table>

Create Plugin From Custom Post Type

1. Create folder with name “rar-portfolio” in plugins folder.
2. Create a file name with “portfolio.php”.
3. Add below code into “portfolio.php”.

Note: Create custom post type on plugin activation with short code

We used this custom post type : Create and display custom post type with Texonomy, Metabox and Tag


<?php
/**
 * Plugin Name: RAR Portfolio
 * Plugin URI: http://rarthemes.com
 * Description: Create custom post type on plugin activation with short code
 * Version: 1.0.0
 * Author: Ravi Radadiya
 * Author URI: http://rarthemes.com
 * License: GPL2
 */
 
/***** Start custom post type - Portfolios *****/
function portfolios_custom_init() {
$labels = array(
'name' => __('Portfolios','themename'),
'singular_name' => __('portfolios','themename'),
'add_new' => __('Add New','themename'),
'add_new_item' => __('Add New Portfolio','themename'),
'edit_item' => __('Edit Portfolio','themename'),
'new_item' => __('New Portfolio','themename'),
'all_items' => __('All Portfolios','themename'),
'view_item' => __('View Portfolios','themename'),
'search_items' => __('Search Portfolio','themename'),
'not_found' => __('No Portfolios found','themename'),
'not_found_in_trash' => __('No Portfolios found in Trash','themename'),
'parent_item_colon' => '',
'menu_name' => __('Portfolios','themename')
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'portfolios' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor','thumbnail')
 
);
register_post_type( 'portfolios', $args );
register_taxonomy("portfolio-categories",
array("portfolios"),
array("hierarchical" => true,
'show_admin_column'   => true,
"label" => "Portfolio Categories",
"singular_label" => "Portfolio Categories",
"rewrite" => array( 'slug' => 'portfolio_category' ,
 
)));
 
register_taxonomy("portfolio-tag",
array("portfolios"),
array("hierarchical" => false,
'show_admin_column'   => true,
"label" => "Portfolio Tag",
"singular_label" => "Portfolio tag",
"rewrite" => array( 'slug' => 'portfolio_tag' ,
 
)));
 
}
add_action( 'init', 'portfolios_custom_init' );
 
/*****  Custom Meta Box - portfolios *****/
 
add_action( 'add_meta_boxes', 'meta_box_portfolio' );
function meta_box_portfolio()
{
add_meta_box( 'meta_box_portfolio_id', 'Enter Portfolio info', 'portfolio_website_info', 'portfolios', 'normal', 'high' );
}
function portfolio_website_info( $post )
{
$values = get_post_custom( $post->ID );
$portfolio_url = isset( $values['portfolio_url'] ) ? esc_attr( $values['portfolio_url'][0] ) : '';
$portfolio_text = isset( $values['portfolio_text'] ) ? esc_attr( $values['portfolio_text'][0] ) : '';
$portfolio_image = isset( $values['portfolio_image'] ) ? esc_attr( $values['portfolio_image'][0] ) : '';
 
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>

<p>Portfolio URL</p>
<input type="text" name="portfolio_url" value="<?php echo esc_url( $portfolio_url ); ?>" class="widefat" placeholder="Portfolio Url" />
<p>Portfolio Text</p>
<input type="text" name="portfolio_text" value="<?php echo esc_attr( $portfolio_text ); ?>" class="widefat" placeholder="Portfolio Text" />
<p>Portfolio Image</p>
<input id=""  type="text" class=" mytheme_media_url upload" name="portfolio_image" value="<?php echo esc_attr( $portfolio_image ); ?>" placeholder="No file chosen"  />
<?php if(!empty($instance['image'])) { ?>
<img src="<?php echo $instance['image']; ?>"  />
<?php } ?>
<input id="mytheme_image_uploader"  class="button mytheme_media_upload" type="button" value="Upload" />
<?php
} 
add_action( 'save_post', 'portfolio_meta_box_save' );
function portfolio_meta_box_save( $post_id )
{
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
if( isset( $_POST['portfolio_url'] ) ) update_post_meta( $post_id, 'portfolio_url', esc_url( $_POST['portfolio_url'] ) );
if( isset( $_POST['portfolio_text'] ) ) update_post_meta( $post_id, 'portfolio_text', esc_attr( $_POST['portfolio_text'] ) );
if( isset( $_POST['portfolio_image'] ) ) update_post_meta( $post_id, 'portfolio_image', esc_attr( $_POST['portfolio_image'] ) );
}
/*** end portfolio post type ***/

/* Register activation hook */
function portfolio_plugin_activation() {
    portfolios_custom_init();
   // flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'portfolio_plugin_activation' );

/* Display posts */

function display_portfolio(){
	?>
<div class="row">
  <?php
$legal_portfolio_args = array(
'paged' => $paged,
'orderby' => 'post_date',
'order' => 'ASC',
'post_type' => 'portfolios',
'post_status' => 'publish'
);
$legal_portfolio = new WP_Query( $legal_portfolio_args );
while ( $legal_portfolio->have_posts() ) { $legal_portfolio->the_post();
?>
  <div class="col-md-6 col-sm-6 attorneys">
    <div class="our-section-box">
      <?php if ( has_post_thumbnail() ) { ?>
      <a href="<?php the_permalink(); ?>" target="_blank">
      <div class="col-md-12 no-padding our-box-left">
        <?php the_post_thumbnail( 'legal-ourteam-thumbnail-image', array( 'alt' => get_the_title(), 'class' => 'img-responsive') ); ?>
      </div>
      </a>
      <?php } ?>
      <div class="col-md-12 our-box-right">
        <h4>
          <?php the_title(); ?>
        </h4>
        <?php the_content(); ?>
        <?php
echo 'URL: '.  get_post_meta( get_the_ID(), 'portfolio_url', true );
echo '<br>text: '. get_post_meta( get_the_ID(), 'portfolio_text', true );
echo '<br>Image: '. get_post_meta( get_the_ID(), 'portfolio_image', true );
echo '<br>Category: '; foreach((get_the_terms($post->ID, 'portfolio-categories')) as $term) { echo $term->name. ' ,'  ; }
echo '<br>tag: '; foreach((get_the_terms($post->ID, 'portfolio-tag')) as $term) { echo $term->name. ' ,'  ; }
?>
      </div>
    </div>
  </div>
  <?php } ?>
</div>
<?php
}

/* Add short code */

add_shortcode('rar_portfolio', 'portfolio_shortcode');
function portfolio_shortcode(){ 
	return display_portfolio();
}

Approve Posts, Added by Public Users in WordPress

1. All Users can add post from fronted.
2. After submitting post will display on admin posts list as pending mode.
3. Post will display on fronted after publishing post by admin.

https://wordpress.org/plugins/user-submitted-posts/screenshots/

Disable wordpress admin for non administer users

/* Disable wordpress admin for non administer users*/

add_action( 'init', 'blockusers_init' );
function blockusers_init() {
    if ( is_admin() && ! current_user_can( 'administrator' ) &&
       ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
        wp_redirect( home_url() );
        exit;
    }
}

Add Download Button and Counter Using WordPress Ajax

Add below code into functions.php

/* Enque script for ajax */
add_action('wp_enqueue_scripts', 'download_counter_enqueue');
function download_counter_enqueue() {
	wp_register_script('ajax-download-script', get_template_directory_uri() . '/js/dowload-counter.js', array('jquery'));
	wp_enqueue_script('ajax-download-script');
	wp_localize_script('ajax-download-script', 'ajax_download_object', array('ajaxurl' => admin_url('admin-ajax.php')));
}  

/* Insert download counter using ajax */
function download_counter() {
    //update_post_meta(45, 'themes_downloads', 45);
    $wp_id = $_POST['wp_id'];
    $wp_downloaded = $_POST['wp_downloaded'];
   
    $wp_downloads_count = $wp_downloaded + 1;
    $wp_downloads = update_post_meta($wp_id, 'wp_downloads', $wp_downloads_count );
}
add_action( 'wp_ajax_download', 'download_counter' );
add_action( 'wp_ajax_nopriv_download', 'download_counter' );

Create new javascript file (dowload-counter.js)

/* WP themes Download counter */	
jQuery(document).ready(function($) {
	 $("a").click(function(){
     $("#ajaxform").submit();
     $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_download_object.ajaxurl,
            data: {
                    'action': 'download', //calls wp_ajax_nopriv_ajaxdownload
                    'wp_id': $('form#ajaxform #wp_id').val(),
                    'wp_downloaded': $('form#ajaxform #wp_downloaded').val(),
                  },
            success: function(){ }
        });
  });
});

Add below form and button code in sigle file (single.php)

$wp_downloaded = get_post_meta($post->ID, 'wp_downloads', true); ?>
<form id="ajaxform" action="ajaxform" method="post">
    <input type="hidden" name="wp_id" id="wp_id" value="<?php echo $post->ID; ?>" />
    <input type="hidden" name="wp_downloaded" id="wp_downloaded" value="<?php echo $wp_downloaded; ?>" />
    <input type="submit" name="submit" style="display:none;"/>
</form>
<a href="#">Download</a> <?php echo $wp_downloaded;

WordPress Practical Interview questions – fronted

<?php

//=====================================================================
//	Display posts list
//=====================================================================

$args = array( 
			'post_type' => 'post', 
		);
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();	
endwhile;

//=====================================================================
//	Display posts meta
//=====================================================================

echo get_post_meta(get_the_ID(),'meta_key',true); 

//=====================================================================
//	Display sidebar
//=====================================================================

if ( is_active_sidebar( 'sidebar-1' )  ) :
	dynamic_sidebar('sidebar-1');
endif;	

//=====================================================================
//	WordPress Loop
//=====================================================================

if ( have_posts() ) : // check post is avalable or not,if yes then will go for next step
while ( have_posts() ) : // if you had configured your WordPress reading settings to display five posts on the home page then while loop five times and then stop.
the_post(); // This sets up the post and allows us to retrieve any part of the post including the content, the publication date, the author, the category etc.

// the_post function code
function the_post() {
    global $wp_query;
    $wp_query->the_post();
}

if ( have_posts() ) : while ( have_posts() ) : the_post();
	// DO SOMETHING WITH EACH POST THAT WE FOUND
	endwhile; else: 
	// DO SOMETHING IF NOTHING WAS FOUND
endif;

//=====================================================================
//	WordPress WP Query
//=====================================================================

// The retrieved dataset is stored in the $wp_query object.
// List of Query Vars (https://codex.wordpress.org/WordPress_Query_Vars#Query_variables)
// If you use the_post() with your query, you need to run "wp_reset_postdata()" afterwards to have Template Tags use the main query’s current post again.

// Example 1
$query = new WP_Query('cat=14,15 & posts_per_page=3 & order=ASC');
while ( $query->have_posts() ) : $query->the_post();
	// Your code here
endwhile;
wp_reset_postdata(); // Restore original Post Data

// Example 2
// Full list of parameters (https://codex.wordpress.org/Class_Reference/WP_Query#Parameters)
// Methods and properties (https://codex.wordpress.org/Class_Reference/WP_Query#Methods_and_Properties)
$args = array( 'arg_1' => 'val_1', 'arg_2' => 'val_2' );
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
	while ( $query->have_posts() ) : $query->the_post(); 
		// Your code here
	endwhile;
	} else {
        // no posts found
	}
wp_reset_postdata();

//=====================================================================
//	WordPress WP Meta Query
//=====================================================================

// To build a query based on a single custom field, we just need one or more of the following arguments:
//(meta_key, meta_value, meta_type, meta_compare)

$args = array( 
		'post_type' => 'my_post_tname',
		
		// For single key and value
		'meta_key'     => 'my_meta_key',
		'meta_value'   => 'value1',	
		
		// For multiple key and value
		'meta_query' => array(
			array(
				'key'     => 'my_meta_key',
				'value'   => array ('value1','value2'),
			),
			array(
				'key'     => '_thumbnail_id',
				'compare'   => 'EXISTS',
		),)
);
$query = new WP_Query( $args );
while ( $loqueryop->have_posts() ) : $query->the_post();
	echo 'Name : '. get_post_meta(get_the_ID(),'my_meta_key',true); 
endwhile;
wp_reset_postdata();	

//=====================================================================
//	WordPress WP Tax Query
//=====================================================================

$args = array( 
		'post_type' => 'my_post_tname',
		'tax_query' => array(
			 array(
				'taxonomy' => 'projects',
				
				// With slug name
				'field' => 'slug',
				'terms' => array('apartment','farm-house'),
				
				// With ID
				'terms' => array('3','5'),
				
				'operator' => 'NOT IN',
				
		)),	
);

//=====================================================================
//	Custom Search form
//=====================================================================

// Copy and pest your default search form code in perticular page and add your custom post type name in below hidden input field. 
<input type="hidden" name="post_type" value="portfolio">

// Change search function globally to search only post, page and portfolio post types
function prefix_limit_post_types_in_search( $query ) {
    if ( $query->is_search ) {
        $query->set( 'post_type', array( 'post','page', 'portfolio' ) );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'prefix_limit_post_types_in_search' );




%d bloggers like this: