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.

Monday, 14 April 2014

WordPress Blog Too Slow? 7 Ways You Can Speed It Up Again In Minutes

Your WordPress site is slow, and you’re losing page views and revenue because of it. But you’re also busy – I get it. Here’s seven speed tips you could have a crack at on your lunch break – they’re so simple and easy.

Optimize Images

This is a two-parter. The first thing is to equip yourself with the knowledge of using the best format for the job. When we talk about images used on the web, it’s generally restricted to either a JPG or PNG. PNG is a lossless format, best suited to simple images and illustrations, or screenshots. JPG is a lossy format suitable for photographs – it can retain the detail at varying levels of quality. If you’re uploading photographs in PNG format, you probably have images that are up to ten times as big as they would be if you used JPG. Just bear in mind that JPG loses a little detail and clarity each time modifications are made and it’s saved – so always export from your originals.
  • Use JPG for photos, but only export once.
  • Use PNG for illustrations and screenshots
Second – even if you are using the the correct image format, chances are you could still be making savings by compressing and optimizing those images. EWWW Image Optimizer is a simple plugin that will do this for automatically as you upload them to WordPress. You can also run the optimizer over all your existing images, potentially shaving up to 95% with no noticeable loss in quality; and even convert to and from PNG and JPG if you did choose the wrong format. That alone will make a huge difference to loading time for the end user. What are you waiting for?

Friday, 28 March 2014

Import/Export Widget Settings in WordPress


Sometimes when moving WordPress sites, you may need to save and reuse widget settings from one WordPress installation to another. If a site has just a few widgets, then you can probably do that manually. However, if there are many widgets inmultiple sidebars and widget areas, then you need a better solution. In this article, we will show you how to import/export widget settings in WordPress.
First thing you need to do is install and activate the Widget Settings Import/Exportplugin. Upon activation, go to Tools » Widget Settings Export and select the widgets you want to export and click on Export Widget Settings Button. The plugin will now export all your currently active widgets in widget_data.json file.

To restore these widgets in another WordPress installation, you will need to install and activate the Widget Settings Import/Export plugin on that site as well. Once you have activated the plugin, go to Tools » Widget Settings Import and click on the Select File button.
Locate the JSON file you downloaded earlier and then click on the Show Widgets Settings button. The plugin will now load widget data from the imported file and will show you the list of widgets. Select the widgets you want to import and click onImport Widget Settings to proceed. All your widgets will be restored to appropriate sidebars.
Please note that if you have active widgets added to your site by a plugin, then you may not be able to import those widgets until you have those plugins installed on the target website as well.
 

Monday, 24 March 2014

Bulk Install Your Favorite Plugins in WordPress

Every WordPress user has their favorite plugins which they like to use on all their sites. We have our own set of must use WordPress plugins. In the past, you had to manually install each individual plugin for every site that you setup. In this article, we will show you how to bulk install your favorite WordPress plugins. This will come in handy if you manage multiple WordPress sites and need to setup new WordPress sites regularly.
First thing you need to do is install and activate the WP Install Profiles plugin. After activation, you need to go to Plugins » Bulk Install Profiles.

You will see a default list of plugins there at first. If you want to use a plugin from that list, then keep the ones you want to use and delete the rest. You can also add new plugins to this list as long as they’re available on WordPress.org.
To add a plugin, you need to add the name used in the plugin’s URL slug. For example, if you want to add floating social bar, then you will enter either floating-social-bar or floating social bar.
Once you have entered all the plugins that you want to install, you can give this list a profile name, e.g. MyFavoritePlugins. After that you can save the profile, or click onDownload plugins and save profile.

Thursday, 20 March 2014

Paginate Comments in WordPress

Have you noticed that your post with lot of comments load slower than your other posts that has barely any comments. Because your most commented posts are usually the most popular, you want these posts to load fast. In this article, we will show you how to paginate comments in WordPress to speed up your post load time.
First thing you need to do is login to your WordPress admin area and go to Settings » Discussions. Next look at the section where it says Break comments into pages. Simply select the number of comments you want on each page, and how you want to display them.
http://shrikantitservices.blogspot.in/

Once you do this, based on your theme styling, either you will see a numeric pagination or you will see Previous / Next comment links.
Several users have reported that sometimes posts with a lot comments return awhite screen of death because it exhausts their memory.
If it doesn’t cause a white screen of death, then posts with a lot of comments tend to be really really slow. We strongly recommend that you paginate your comments.
Note: you can also paginate posts by splitting a long post into multiple pages.

Wednesday, 19 March 2014

Display a User’s IP Address in WordPress

Recently one of our users asked us if it was possible to detect and display individual visitors’ IP address in WordPress. Our answer was of course it is. In this article, we will show you how to display user’s IP address in WordPress.
You can use this to create your own IP detection site. This way when a website visitor views your site, they can see their own IP address.
All you have to do is paste the following snippet in your theme’s functions.php file
// Display User IP in WordPress

function wpb_show_ip()
{
        $user_ip = $_SERVER['REMOTE_ADDR'];
        return $user_ip;
}

add_shortcode('show_ip', 'wpb_show_ip');
 
Next thing you need to do is add the following shortcode in your post, page, or in a sidebar widget.
[show_ip]
If you’re using the shortcode in your sidebar text widget, and it is not working, then you need to make sure that you enable shortcode for sidebar widgets.
 

Thursday, 13 March 2014

What is jQuery filters ?

The jQuery filters enhance jQuery selectors by providing additional logic. And this actually sharpen the power of selectors.
Lets start with some basic filters for example :
  • The odd and even filters- find odd and even elements(zero-indexed)
  • Lets say a table with  5 rows
  • :gt & :lt They stands for greater than or less than.
  • :gt gives you children greater than index .
  • :lt gives you children lesser than index.
  •  Lets the table with 5 rows have elements(0,1,2,3,4).
  • ("tr:gt(3)") will gives rows 3 & 4.
  • ("tr:lt(3)") will gives rows 0 & 1.
Types of jQuery filter
Some of the main types are :
  • Basic filter
  • Child filter
  • Content filter
  • Visibility filter.
Uses of JQuery filter
Some of the key uses are given below :
  • It is very similar to selector in fact we can say that it is a type of selector to enhance the functionality of selector.
  • We can select filter according to their position.
  • We can select filter according to tag name.
  • We can select filter according to child, last-child ,nth child ,only child.
  • We can select filter according to their visibility.
  • We can select filter according to sibling, adjacent, or descendant etc.
Use of jQuery attribute filters
Using jQuery attribute filters make it easy to select and modify particular attributes in your html DOM.
Given below is the demonstration how you can apply filters on attribute ,here we are using "a href " attribute of html DOM :
  • Using it , you can hide all the link in your html page as : $("a[href]").toggle();.
  • But if you want to hide one link , you can do it as : $("a[href='http://www.ai.com/']").toggle();
  • If you want to hide the link which has "google" in href.
  • You can also hide the links which ends with "org" as  $("a[href$='org']").toggle();
  • You can also hide the link which starts like " http://doc " as : $("a[href^='http://docs']").toggle();

jQuery selectors


In this tutorial we are discussing jQuery selectors.
The jQuery selectors are one of the main feature in jQuery library .These selectors uses CSS syntax to allow page developer to easily identify the elements of page to operate upon with jQuery library methods. For using JQuery library most effectively , you must be familiar with  jQuery selectors.
Syntax pattern of jQuery selector :
$.(selector).methodName();
The selector is a string expression that identify the element on which the the method has to be implemented. For example :
$("p").click();
You can also hide the paragraph as follows :
$("p").hide();
You can also apply the CSS class to any element as :
$("p").addClass('box');
Types of jQuery selectors :
There are three categories of jQuery selector :
1.Basic CSS Selector
2.Positional Selector
3.Custom jQuery Selectors.

how to Find .htaccess File on Your WordPress Site

Recently, we advised a user to delete .htaccess file from their site to solve a common WordPress error. The user was unable to find their .htaccess file and thought that there was something wrong with his website. For beginners, things like this can be very confusing. In this article, we will show why you can’t find .htaccess file on your WordPress site, and how to create one when needed.
What is .htaccess file?

.htaccess file is a server configuration file which tells your server how to handle certain things on your website. Like how to redirect users, password protect admin area, or protect some directories, etc.
The dot before the file name indicates that it is a hidden file. When you are accessing your web server through FTP, you will not be able to see .htaccess file unless your FTP client is forced to show hidden files.

Why You Can’t Find .htaccess File?

The most common reason for this is that your WordPress site has not generated a .htaccess file yet. WordPress generates .htaccess file for the first time when you set up pretty permalinks on Settings » Permalinks screen. All you need to do is to click on Save Changes button on the permalinks screen and WordPress will generate a .htaccess file in your site’s root directory.


Monday, 10 March 2014

How to Remove Numbers from WordPress page and posts URLs



Permalink URL Structure

WordPress has built in support for SEO friendly URL structure. All you need to do is to open Settings » Permalinks page in the admin area and choose a URL structure for your site. There are a number of options available. We recommend choosing a URL structure that shows your post title in the URL because it is SEO friendly and will help others discover your site in search engines. Once you have setuppermalinks you need to save your changes.

Sunday, 9 March 2014

How Removing Dashboard Menus

I don't know about you, but there's some parts of the Dashboard I never use, meaning they're just left to bulk up the menu. This is unnecessary, and can easily be fixed by removing them with a function. It's a very common tweak that I use in almost most cases with my own blogs.
In the example below, we've removed the Links item, but you simply have to add in another item to the array to remove another.

function remove_menus () {
global $menu;
        $restricted = array(__('Links'));
        end ($menu);
        while (prev($menu)){
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
        }
}
add_action('admin_menu', 'remove_menus');
 
for example to remove Links and media menu on damin dashboard
 
$restricted = array(__('Links'), __('Media'));
 

how to Removing Dashboard Widgets

Just as we can add our own custom dashboard widgets, we can remove specific dashboard widgets with ease.
function disable_default_dashboard_widgets() {
 
    remove_meta_box('dashboard_right_now', 'dashboard', 'core');
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'core');
    remove_meta_box('dashboard_incoming_links', 'dashboard', 'core');
    remove_meta_box('dashboard_plugins', 'dashboard', 'core');
    remove_meta_box('dashboard_quick_press', 'dashboard', 'core');
    remove_meta_box('dashboard_recent_drafts', 'dashboard', 'core');
    remove_meta_box('dashboard_primary', 'dashboard', 'core');
    remove_meta_box('dashboard_secondary', 'dashboard', 'core');
}
add_action('admin_menu', 'disable_default_dashboard_widgets');

How to add custom dashboard widgets



The WordPress dashboard is a layout for widgets, but some of them are, quiet frankly, useless. I certainly remove quite a lot of them from my dashboard, such as the WordPress news and under-featured QuickPress.

With the code below, we can add our own widgets to the dashboard. This can be useful to add custom stats, or maybe to provide contextual help. It's pretty simple to do so, simply place whatever you want to appear within the second function. Make sure you replace your name with the third parameter of the function on line 3 too.


function my_custom_dashboard_widgets() {
global $wp_meta_boxes;
wp_add_dashboard_widget('custom_help_widget', 'My Widget Title', 'custom_dashboard_help');
}
function custom_dashboard_help() {
echo 'My widget content';
}
add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');