Sunday, 19 October 2014

Example AJAX with JSON, jQuery, PHP and MySQL

In the index.php file I connect to the database and I load the name of the products, one for each div. Each div has an id which is the id of the product (also retrieved from the database) and a class: name_product
I also built a second div which will load product data. This second div will have an id: “data” + id of the product and a class: data_product
Step 3 – code.js
$(document).ready(function() {
//Tutorial - www.Ajax101.com

$('.name_product').click(function() {
//we get the id of the selected product
var id = this.getAttribute('id');
//we create the object with the product id
var data = {
idProduct : id
}
//we get the selected div
var div = $('#' + id);
//if the div does not have the class "loaded", we make ajax request
if (!div.hasClass("loaded")) {
$.ajax({
data : data,
url : 'data.php',
global : false,
type : "GET",
dataType : "html",
async : false
}).done(function(result) {
//decode the JSON object received
var data_product = JSON.parse(result);
//we select the div to load the data of the selected product
var datadiv = document.getElementById('data' + data_product[0].id);
datadiv.innerHTML = "";
datadiv.innerHTML += "Description: " + data_product[0].description;
datadiv.innerHTML += "<br>Price: " + data_product[0].price + " €<br/>";
});
}
//we add the class loaded
div.addClass("loaded");
});
});

data.js file will run each time that we select a product. It will make an AJAX request to data.php by passing the id of the selected product. In the second div, paint the data received from data.php
Step 4 – data.php
<?php
$con = mysql_connect("localhost", "root", "root");

if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("shop", $con);
$id=$_GET["idProduct"];
$result=mysql_query("SELECT * FROM products WHERE id='$id'");
$productArray = array();
while ($products=mysql_fetch_assoc($result)) {
$productArray[] = array_map('utf8_encode', $products);
}
//we send the array as JSON object
echo json_encode($productArray);
?>

File “data.php” receive the data object with the attribute idProduct. We connect to the database and select the product that has that id
https://asmclk.com/click.php?aff=105539&camp=148257&sub1=

Wednesday, 2 July 2014

How to Show Empty Categories in WordPress Widgets

By default the WordPress category widget does not show empty categories. Recently a new user asked us if it was possible to display empty categories in WordPress widget to help with his local development. In this article, we will show you how to display empty categories in WordPress widgets.
First thing you need to do is add this simple code snippet in your child theme‘sfunctions.php file or a site specific plugin.


add_filter( 'widget_categories_args', 'wpb_force_empty_cats' );
function wpb_force_empty_cats($cat_args) {
    $cat_args['hide_empty'] = 0;
    return $cat_args;
}


This code hooks up our custom function wpb_force_empty_cats towidget_categories_args filter. Inside our function we have modified the optionhide_empty and set it to false.
That’s all, you can now drag and drop categories widget to any sidebar or widget ready area on your WordPress site. The category widget will now display empty categories as well.
If you’re working on a local development environment, then we recommend that you add some dummy content to your website for testing purposes.
Also don’t forget to check out our guide on how categories and tags work in WordPress.

Monday, 23 June 2014

Creating a Custom Post Type Manually


First we will show you a quick and fully working example so that you understand how it works. Take a look at this code:
// Our custom post type function
function create_posttype() {

 register_post_type( 'movies',
 // CPT Options
  array(
   'labels' => array(
    'name' => __( 'Movies' ),
    'singular_name' => __( 'Movie' )
   ),
   'public' => true,
   'has_archive' => true,
   'rewrite' => array('slug' => 'movies'),
  )
 );
}
// Hooking up our function to theme setup
add_action( 'init', 'create_posttype' );
What this code does is that it registers a post type 'movies' with an array of arguments. These arguments are the options of our custom post type. This array has two parts, the first part is labels, which itself is an array. The second part contains other arguments like public visibility, has archive, and slug that will be used in URLs for this post type.
Now lets take a look at a detailed piece of code that adds more options to your custom post type.
/*
* Creating a function to create our CPT
*/

function custom_post_type() {

// Set UI labels for Custom Post Type
 $labels = array(
  'name'                => _x( 'Movies', 'Post Type General Name', 'twentythirteen' ),
  'singular_name'       => _x( 'Movie', 'Post Type Singular Name', 'twentythirteen' ),
  'menu_name'           => __( 'Movies', 'twentythirteen' ),
  'parent_item_colon'   => __( 'Parent Movie', 'twentythirteen' ),
  'all_items'           => __( 'All Movies', 'twentythirteen' ),
  'view_item'           => __( 'View Movie', 'twentythirteen' ),
  'add_new_item'        => __( 'Add New Movie', 'twentythirteen' ),
  'add_new'             => __( 'Add New', 'twentythirteen' ),
  'edit_item'           => __( 'Edit Movie', 'twentythirteen' ),
  'update_item'         => __( 'Update Movie', 'twentythirteen' ),
  'search_items'        => __( 'Search Movie', 'twentythirteen' ),
  'not_found'           => __( 'Not Found', 'twentythirteen' ),
  'not_found_in_trash'  => __( 'Not found in Trash', 'twentythirteen' ),
 );
 
// Set other options for Custom Post Type
 
 $args = array(
  'label'               => __( 'movies', 'twentythirteen' ),
  'description'         => __( 'Movie news and reviews', 'twentythirteen' ),
  'labels'              => $labels,
  // Features this CPT supports in Post Editor
  'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
  // You can associate this CPT with a taxonomy or custom taxonomy. 
  'taxonomies'          => array( 'genres' ),
  /* A hierarchical CPT is like Pages and can have
  * Parent and child items. A non-hierarchical CPT
  * is like Posts.
  */ 
  'hierarchical'        => false,
  'public'              => true,
  'show_ui'             => true,
  'show_in_menu'        => true,
  'show_in_nav_menus'   => true,
  'show_in_admin_bar'   => true,
  'menu_position'       => 5,
  'can_export'          => true,
  'has_archive'         => true,
  'exclude_from_search' => false,
  'publicly_queryable'  => true,
  'capability_type'     => 'page',
 );
 
 // Registering your Custom Post Type
 register_post_type( 'movies', $args );

}

/* Hook into the 'init' action so that the function
* Containing our post type registration is not 
* unnecessarily executed. 
*/

add_action( 'init', 'custom_post_type', 0 );


 

Creating a Custom Post Type Manually


First we will show you a quick and fully working example so that you understand how it works. Take a look at this code:
// Our custom post type function
function create_posttype() {

 register_post_type( 'movies',
 // CPT Options
  array(
   'labels' => array(
    'name' => __( 'Movies' ),
    'singular_name' => __( 'Movie' )
   ),
   'public' => true,
   'has_archive' => true,
   'rewrite' => array('slug' => 'movies'),
  )
 );
}
// Hooking up our function to theme setup
add_action( 'init', 'create_posttype' );
What this code does is that it registers a post type 'movies' with an array of arguments. These arguments are the options of our custom post type. This array has two parts, the first part is labels, which itself is an array. The second part contains other arguments like public visibility, has archive, and slug that will be used in URLs for this post type.
Now lets take a look at a detailed piece of code that adds more options to your custom post type.
/*
* Creating a function to create our CPT
*/

function custom_post_type() {

// Set UI labels for Custom Post Type
 $labels = array(
  'name'                => _x( 'Movies', 'Post Type General Name', 'twentythirteen' ),
  'singular_name'       => _x( 'Movie', 'Post Type Singular Name', 'twentythirteen' ),
  'menu_name'           => __( 'Movies', 'twentythirteen' ),
  'parent_item_colon'   => __( 'Parent Movie', 'twentythirteen' ),
  'all_items'           => __( 'All Movies', 'twentythirteen' ),
  'view_item'           => __( 'View Movie', 'twentythirteen' ),
  'add_new_item'        => __( 'Add New Movie', 'twentythirteen' ),
  'add_new'             => __( 'Add New', 'twentythirteen' ),
  'edit_item'           => __( 'Edit Movie', 'twentythirteen' ),
  'update_item'         => __( 'Update Movie', 'twentythirteen' ),
  'search_items'        => __( 'Search Movie', 'twentythirteen' ),
  'not_found'           => __( 'Not Found', 'twentythirteen' ),
  'not_found_in_trash'  => __( 'Not found in Trash', 'twentythirteen' ),
 );
 
// Set other options for Custom Post Type
 
 $args = array(
  'label'               => __( 'movies', 'twentythirteen' ),
  'description'         => __( 'Movie news and reviews', 'twentythirteen' ),
  'labels'              => $labels,
  // Features this CPT supports in Post Editor
  'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
  // You can associate this CPT with a taxonomy or custom taxonomy. 
  'taxonomies'          => array( 'genres' ),
  /* A hierarchical CPT is like Pages and can have
  * Parent and child items. A non-hierarchical CPT
  * is like Posts.
  */ 
  'hierarchical'        => false,
  'public'              => true,
  'show_ui'             => true,
  'show_in_menu'        => true,
  'show_in_nav_menus'   => true,
  'show_in_admin_bar'   => true,
  'menu_position'       => 5,
  'can_export'          => true,
  'has_archive'         => true,
  'exclude_from_search' => false,
  'publicly_queryable'  => true,
  'capability_type'     => 'page',
 );
 
 // Registering your Custom Post Type
 register_post_type( 'movies', $args );

}

/* Hook into the 'init' action so that the function
* Containing our post type registration is not 
* unnecessarily executed. 
*/

add_action( 'init', 'custom_post_type', 0 );


 

Thursday, 1 May 2014

Custom Post type

 Add this following code in your function.php file in to the theme

/******************************************************/
add_action( 'init', 'register_cpt_event' );

function register_cpt_event() {

    $labels = array(
        'name' => _x( 'events', 'event' ),
        'singular_name' => _x( 'event', 'event' ),
        'add_new' => _x( 'Add New', 'event' ),
        'add_new_item' => _x( 'Add New event', 'event' ),
        'edit_item' => _x( 'Edit event', 'event' ),
        'new_item' => _x( 'New event', 'event' ),
        'view_item' => _x( 'View event', 'event' ),
        'search_items' => _x( 'Search events', 'event' ),
        'not_found' => _x( 'No events found', 'event' ),
        'not_found_in_trash' => _x( 'No events found in Trash', 'event' ),
        'parent_item_colon' => _x( 'Parent event:', 'event' ),
        'menu_name' => _x( 'events', 'event' ),
    );

    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'description' => 'new event',
        'supports' => array( 'title', 'editor', 'thumbnail' ),
       
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
       
       
        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => true,
        'capability_type' => 'post'
    );

    register_post_type( 'event', $args );
}
/**************************************************************/   

Monday, 21 April 2014

EXPORT FORM DATA TO EXCEL (CSV) IN PHP

In this tutorial you are going to learn how to download an excel report after filling a HTML form.
MySQL is not used in this tutorial, just a simple example showing how to generate Excel file using core PHP functions.
<?php

//give a filename
$filename = "myexcel.csv";


//set headers to download the file
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);

//set an array
$cells = array("Column1", "Column2", "Column3");

$file = fopen('php://output', 'w');           

fputcsv($file,$cells);

fclose($file);


?>
When you run this code on a web browser, a CSV (myexcel.csv) file will immediately download with  the values given in the array $cells[].
I have used php://output stream which sends the output from Apache server to the browser.
fputcsv() - this function plays the main role in the above script, it helps us to create the CSV file from the array $cells[].
Now, lets move to the dynamic part,
Create a form in HTML, see the below (index.html):
<html>
<body>
    <form action="excel.php" method="post">
        <table>
            <tr><td>Name</td><td><input type="text" name="name" /></td></tr>
            <tr><td>Email</td><td><input type="text" name="email" /></td></tr>
            <tr><td>Location</td><td><input type="text" name="location" /></td></tr>
            <tr><td>&nbsp;</td><td><input type="submit" /></td></tr>
        </table>
    </form>
</body>
</html>

PHP script – slightly modified from the first script (excel.php):
<?php

//give a filename
$filename = "myexcel.csv";


//set headers to download file
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);

$file = fopen('php://output', 'w');           

//set the column names
$cells[] = array('Name', 'Email', 'Location');

//pass all the form values
$cells[] = array($_POST['name'], $_POST['email'], $_POST['location']);

foreach($cells as $cell){
    fputcsv($file,$cell);
}


fclose($file);


?>
if you compare the first script and this one above, you can see there is a difference in $cells[]  variable which became multi-dimensional array and also I’m looping through each array usingforeach()
Basically first iteration will pass the column names which is hard coded, the second iteration will pass the dynamic values from $_POST.