Monthly Archives: January 2017

Create Category and Sub Category Tree in PHP

Create table


CREATE TABLE IF NOT EXISTS `category` (
  `cid` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `parent` int(11) NOT NULL,
  PRIMARY KEY (`cid`)
);

Create code file


<?php

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

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

function fetchCategoryTreeList($parent = 0, $user_tree_array = '') {
 
    if (!is_array($user_tree_array))
    $user_tree_array = array();
 
  $sql = "SELECT `cid`, `name`, `parent` FROM `category` WHERE 1 AND `parent` = $parent ORDER BY cid ASC";
  $query = mysql_query($sql);
  if (mysql_num_rows($query) > 0) {
     $user_tree_array[] = "<ul>";
    while ($row = mysql_fetch_object($query)) {
	  $user_tree_array[] = "<li>". $row->name."</li>";
      $user_tree_array = fetchCategoryTreeList($row->cid, $user_tree_array);
    }
	$user_tree_array[] = "</ul>";
  }
  return $user_tree_array;
}
?>

<ul>
  <?php
  $res = fetchCategoryTreeList();
  foreach ($res as $r) {
    echo  $r;
  }
?>
</ul>


Advertisements

MySQL Practical Interview questions and Syntax’s


<?php
 
//=====================================================================
//  SELECT
//=====================================================================

SELECT column_name,column_name
FROM table_name;

// If you want all column from database

SELECT * FROM table_name;

// Example

SELECT name, number FROM `tbl1`;

//=====================================================================
//  SELECT DISTINCT
//=====================================================================
 
// DISTINCT means Diffrent
// It can display only unique value, Not repit same value.

SELECT DISTINCT column_name,column_name
FROM table_name;

// Ex
SELECT DISTINCT name FROM tbl1;

//=====================================================================
// SELECT WHERE Clause 
//=====================================================================

SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;

// Ex
SELECT city FROM tbl1
WHERE city='junagadh';

//=====================================================================
// AND & OR Operators
//=====================================================================

// AND - Display result if both condition are true.

SELECT * FROM tbl1
WHERE city='junagadh'
AND name='ravi';

// OR - Display result if either one condition are true.

SELECT * FROM tbl1
WHERE city='junagadh'
OR city='keshod';

//=====================================================================
// ORDER BY Keyword
//=====================================================================

SELECT * FROM tbl1
ORDER BY name ASC, city DESC;

//=====================================================================
// INSERT INTO
//=====================================================================

// used to insert new records in a table.

INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);

//Ex

INSERT INTO `tbl1`(`name`, `number`, `city`) VALUES ('happy','9979745855','divrana');

//=====================================================================
// UPDATE Statement
//=====================================================================

UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

// Ex

UPDATE `tbl1` SET `name`='mama',`number`='123456963',`city`='ahmedabad' WHERE `id` = '137';

//=====================================================================
// DELETE Statement
//=====================================================================

DELETE FROM table_name
WHERE some_column=some_value;

// Delete table

DELETE FROM tbl1

// Delete by value

DELETE FROM tbl1
WHERE name='ravi' AND city='junagadh';

//=====================================================================
// SELECT TOP
//=====================================================================

// Top N record list to return.

SELECT *
FROM tbl1
LIMIT 3;

//=====================================================================
// LIKE Operator
//=====================================================================

// Search by starting with the letter "s"
SELECT * FROM tbl1
WHERE city LIKE 's%';

// Search by ending with the letter "s"
SELECT * FROM tbl1
WHERE city LIKE '%s';

// Search by any single and multi latter "rav" 
SELECT * FROM tbl1
WHERE name LIKE '%rav%';

// Search every latter without "rav" 
SELECT * FROM tbl1
WHERE name NOT LIKE '%rav%';

//=====================================================================
// IN Operator
//=====================================================================

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);

// Ex

SELECT * FROM tbl1
WHERE city IN ('divrana','ahmedabad');

//=====================================================================
// BETWEEN Operator
//=====================================================================

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

// Ex BETWEEN

SELECT * FROM tbl1
WHERE price BETWEEN 135 AND 137;

// Ex NOT BETWEEN 

SELECT * FROM tbl1
WHERE price NOT BETWEEN 135 AND 137;

//=====================================================================
// Aliases
//=====================================================================

// SQL aliases are used to temporarily rename a table or a column heading.

SELECT name AS firstname, number as monumber
FROM tbl1;

//=====================================================================
// NULL Values
//=====================================================================

// NULL values represent missing unknown data.

SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NULL

//=====================================================================
// JOIN
//=====================================================================

// INNER JOIN

// INNER JOIN = JOIN (You cal also use only "join" in syntex)
// Inner join also called simple join
// Inner join ma first table and second table banne ni value hase ej display tharse 

// Syntex ( fk = FOREIGN KEY , PK = PRIMARY KEY )
SELECT fk_table_name.column_name, table_name.column_name
FROM fk_table_name
INNER JOIN table_name
ON fk_table_name.fk_column_name=table_name.pk_column_name;

// EX

SELECT product.p_name, category.c_name
FROM product
INNER JOIN category
ON product.c_id=category.c_id;

// LEFT JOIN

// Left join ma first table ni badhi value display thase ane second table ma nai hoi to false display thase 

SELECT product.p_name, category.c_name
FROM product
LEFT JOIN category
ON product.c_id=category.c_id;

// RIGHT JOIN

// Right join ma second table ni badhi value display thase ane first table ma nai hoi to false display thase 

SELECT product.p_name, category.c_name
FROM product
LEFT JOIN category
ON product.c_id=category.c_id;

// RIGHT JOIN

// Full outer join ma first table and second table ma value nahi hoi e pan display tharse 

SELECT product.p_name, category.c_name
FROM product
FULL OUTER JOIN JOIN category
ON product.c_id=category.c_id;

//=====================================================================
// UNION Operator
//=====================================================================

// UNION operator combines the result of two or more SELECT statements.

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

// Display all duplicate value also
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;






// ============================================================ WITHOUT PHP MYADMIN ============================================================================

//=====================================================================
// CREATE TABLE 
//=====================================================================

CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);

// Ex

CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

//=====================================================================
// Constraints
//=====================================================================

CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);

// NOT NULL

// "P_Id" column and the "LastName" column to not accept NULL values
CREATE TABLE PersonsNotNull
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

// UNIQUE 

CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)

// PRIMARY KEY

CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)

// FOREIGN KEY

CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)

// Add Foreign key when table already created

ALTER TABLE Orders
ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)

// Drop a FOREIGN KEY

ALTER TABLE Orders
DROP FOREIGN KEY fk_PerOrders

//=====================================================================
// DROP
//=====================================================================

// Delete table

DROP TABLE table_name

DROP DATABASE database_name

// Empty table

TRUNCATE TABLE table_name

//=====================================================================
// ALTER TABLE
//=====================================================================

// ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

// Add a column in a table
ALTER TABLE table_name
ADD column_name datatype

// Delete a column in a table
ALTER TABLE table_name
DROP COLUMN column_name

//=====================================================================
// AUTO INCREMENT
//=====================================================================

CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)

Get Last Inserted ID in PHP MySQL


$query = "SELECT c_id FROM category ORDER BY c_id DESC LIMIT 1;";	  
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {  
	echo $c_id = $row['c_id'];
} 

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/

%d bloggers like this: