Friday, July 17, 2015

Wordpress : Adding Multiple Sidebars

Sidebars are great because they allow us to display a lot of useful info, such as related posts, author info, a blog roll, ad spaces and so on. But sidebars can quickly become very busy, and readers may be hard-pressed to find what they’re looking for. So, what about having different sidebars available and displaying the most appropriate one for the post?
The solution.
To apply this hack, duplicate your sidebar.php file and fill it with whatever information we would like to appear. Save the file as sidebar-whatyouwant.php.
Once that’s done, open single.php* file and find the call to theget_sidebar() function:
<?php get_sidebar(); ?>
Replace it with:
<?php $sidebar = get_post_meta($post->ID, "sidebar", true);
get_sidebar($sidebar);
?>
Now when we write a post, create a custom field named sidebar. Set its value as the name of the sidebar that you want to include. For example, if its value isright, WordPress will automatically include sidebar-right.php as a sidebar.

If no custom sidebar field is found, WordPress automatically includes the default sidebar.
*The same can be done with page.php.
This trick is quite simple. The first thing we did was look for a custom field namedsidebar and get its value as a variable. Then, the variable is used as a parameter for the WordPress function get_sidebar(), which allows us to specify a particular file to use as a sidebar.

Friday, July 10, 2015

Differences between Magento 1.0 and Magento 2.0

Magento 1.0Magento 2.0
Folder app/code includes subfolders: core, community, localFolder app/code includes subfolders Magento and Zend. In Magento 1.0,  Magento andZend are subfolders of the folder core
Codes created by developers are located at app/code/local or app/code/communityCodes created by developers are written directly in app/code. There is no difference between local and community
Module declaration file is a xml file in app/etc/modulesEg:  Module Checkout in Magento Core is declared in app/etc/modules/Mage_All.xmlModule declaration file is always module.xml which is written directly to folder etc in the moduleEg:  module Checkout in Magento Core is declared in app/code/Magento/Checkout/etc/module.xml
Layout and template are saved in folder app/designEg:  app/design/frontend/default/default/layoutLayout and template are saved in the folder “View” in the module. The folder is the same level with some folders like: Block, Controller, Helper, Model, etc. in the moduleEg:  app/code/Magento/Hello/view/frontend/layout

Friday, July 3, 2015

Wordpress: Introduction to hooks

What are wordpress hooks

Hooks are provided by WordPress to allow our plugin to 'hook into' the rest of WordPress; that is, to call functions in our plugin at specific times, and thereby set our plugin in motion. There are two types of hooks: Actions (Codex Action Reference) Filters (Codex Filter Reference)

Action Hooks

Action hooks are essentially placeholders. Wherever an action hook is placed, it will execute any code that has been "hooked" to it.

An example of this is the commonly used wp_head action hook, used by many themes and plugins to inject additional CSS stylesheets, processing code or anything else they require to sit between the <head> and </head> tags of their WordPress theme’s XHTML structure. This is the reason for including wp_head(); in all WordPress themes.

To hook on to an action, we create a function in our theme’s functions.php file (or in our plugin’s code) and hook it on using the add_action() function, as follows:

<?php
add_action( 'wp_head', 'wp_actionhook_example' );

function wp_actionhook_example () {

echo '<meta name="description" content="This is the meta description for this page." />' . "
";

}
?>


Filter Hooks

Filters are functions that WordPress passes data through, at certain points in execution, just before taking some action with the data (such as adding it to the database or sending it to the browser screen). Filters sit between the database and the browser (when WordPress is generating pages), and between the browser and the database (when WordPress is adding new posts and comments to the database); most input and output in WordPress passes through at least one filter. WordPress does some filtering by default, and your plugin can add its own filtering.

Custom code is added as a filter using the add_filter() function. The following code adds a sign-off to the end of each blog post, only when viewing the full blog post screen:

<?php
add_filter( 'the_content', 'wp_filterhook_signoff' );

function wp_filterhook_signoff ( $content ) {

if ( is_single() ) {

$content .= '<div class="sign-off">Th-th-th-th-th That\'s all, folks!</div>' . "
";

} // End IF Statement

return $content;

}
?>
The above code adds a new div tag to the end of the content of our blog post, only when on a single blog post screen.

A filter hook is like using the str_replace() function in PHP. You give it some data, manipulate, replace or reformat the data and return the new content out at the end.

Friday, June 26, 2015

Wordpress : function to get different site url

Getting the Home Page URL

  1. bloginfo( 'url' ): displays the home URL as specified in our Reading settings in the admin.
  2. get_bloginfo( 'url' ): fetches the site URL without displaying it.
  3. home_url(): fetches the home page URL without displaying it: use echo esc_url( home_url( '/' ) ); to display the home URL with a trailing slash. This takes two optional parameters: $path if we want to add a path to a specific page or add a trailing slash, and $scheme to specify the scheme for the URL, such as http, https and relative.
  4. get_home_url(): retrieves the URL for the home page, and supports Multisite: we can include the blog ID as a parameter.
  5. site_url(): the URL where WordPress is stored, so if our WordPress installation is in the wordpress subdirectory, this will retrieve the URL http://mysite.com/wordpress. 
  6. get_site_url(): retrieves the site URL without outputting it. Can also be used with parameters to output the URL for a site in a Multisite network, add a path, and use a specific scheme.
  7. network_home_url(): the home URL for the main site in a Multisite network, useful if you want to include a link to the main site in the footer of each site on the network, for example.
  8. network_site_url(): the site URL for the main site in a Multisite Network.
Getting Other Front-End URLs

Other than home page URL, we want url of pages, posts, attachments, and custom post types. Below are the function, we should use:
  • post_permalink(): outputs a link to a post, with the post ID as its parameter.
  • get_page_link(): fetches (but does not output) the link to a page, with the page ID as a parameter.
  • get_permalink(): fetches (but does not output) the permalink for a post or page, with the post or page ID as its parameter.
  • get_category_link(): fetches the link to a category archive, with the category ID as its parameter.
  • get_tag_link(): fetches the link to a tag's archive page, with the tag ID as its parameter.
  • get_post_type_archive_link(): fetches the link to a post type's archive, with the post type as its parameter.
  • get_term_link(): fetches the link to a taxonomy term, with the term and the taxonomy as its parameters.
  • the_attachment_link(): outputs the link to an attachment, with the attachment ID as its first parameter. Use other parameters to define the image size and whether the link will lead to the file itself or its attachment page.
  • get_attachment_link(): fetches the link for an attachment, with the attachment ID as the parameter.
  • wp_get_attachment_link(): also fetches the link to an attachment, but additionally lets us display the image if the attachment is an image, at a size we specify.
  • get_search_link(): retrieves the link to the search page. We can define a query as its parameter, or leave it blank, in which case it will use the current query.

Getting Admin URLs

To get admin url, we should use below function:
  • admin_url(): fetches (but doesn't output) a URL in the admin. We need to include the path to the URL as a parameter and can also include the scheme if needed. So, for example, to output the URL for the screen to create a new post, we would use echo admin_url( 'post-new.php' );.
  • get_admin_url(): is similar to admin_url() but supports Multisite networks: we can include the blog ID as a parameter.
  • edit_post_link(): displays a link to the editing page for a post. It can be used in the loop or outside the loop with the post ID as a parameter.
  • get_edit_post_link(): fetches the link to a post's editing screen, with the post ID as its parameter.
Fetching Files path in our Plugin and Theme Folders
  • get_stylesheet_directory(): retrieves the full server path (not the URL) for the currently activated theme's directory. Use this to call include files rather than to output links.
  • get_stylesheet_directory_uri(): retrieves the URL for the currently activated theme, without a trailing slash. Use it in template files to fetch resources stored in our theme folder: for example, to display an image stored in our theme's images folder, use <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/logo.jpg">.
  • get_bloginfo( 'stylesheet_directory' ) : retrieves the URL for the currently activated theme: using get_stylesheet_directory_uri() is neater.
  • get_template_directory_uri(): is similar to get_stylesheet_directory_uri() but if we're using a child theme, it fetches the URL for the parent theme. Similarly, get_template_directory() works in the same way as get_stylesheet_directory() but for the parent theme.
  • plugins_url(): fetches the absolute URL to the plugins directory (without a trailing slash). It takes two optional parameters: the path to add after the URL, and the plugin which we want the URL to be relative to.
  • plugin_dir_url(): retrieves the URL for the directory a file is in (with a trailing slash), with that file as its parameter. Normally we would use __FILE__ as its parameter to denote the current file.
Below is example to use above 2 functions:

plugins_url( 'includes/myfile.php', __FILE__ );
And to retrieve the same URL using plugin_dir_url():

plugin_dir_url( __FILE__ ) . 'includes/myfile.php' ;
Note that with the second example we have to echo out the path after the function: The second returns a trailing slash and the first doesn't.

Friday, June 19, 2015

PHP: Exploring Regular Expression Syntax

Using Anchors to Match at Specified Positions

Often we're interested in the position of a pattern within a target string, as much as the pattern itself. For example, say we wanted to make sure that a string started with one or more digits followed by a colon. We might try this:

echo preg_match( "/\d+\:/", "12: The Sting" );  // Displays "1"

However, this expression would also match a string where the digits and colon are somewhere in the middle:

echo preg_match( "/\d+\:/", "Die Hard 2: Die Harder" );  // Displays "1"

How can we make sure that the string only matches if the digits and colon are at the start? The answer is that we can use an anchor (also known as an assertion), as follows:

 echo preg_match( "/^\d+\:/", "12: The Sting" );           // Displays "1"
 echo preg_match( "/^\d+\:/", "Die Hard 2: Die Harder" );  // Displays "0"

The caret (^) symbol specifies that the rest of the pattern will only match at the start of the string. Similarly, we can use the dollar ($) symbol to anchor a pattern to the end of the string:

 echo preg_match( "/\[(G|PG|PG-13|R|NC-17)\]$/", "The Sting [PG]" ); // Displays "1"
 echo preg_match( "/\[(G|PG|PG-13|R|NC-17)\]$/", "[PG] Amadeus" );   // Displays "0"

By combining the two anchors, we can ensure that a string contains only the desired pattern, nothing more:

 echo preg_match( "/^Hello, \w+$/", "Hello, world" );  // Displays "1"
 echo preg_match( "/^Hello, \w+$/", "Hello, world!" ); // Displays "0"

The second match fails because the target string contains a non-word character (!) between the searched-for pattern and the end of the string.

We can use other anchors for more control over our matching. Here's a full list of the anchors we can use within a regular expression:

Anchor Meaning
^ Matches at the start of the string
$ Matches at the end of the string
\b Matches at a word boundary (between a \w character and a \W character)
\B Matches except at a word boundary
\A Matches at the start of the string
\z Matches at the end of the string
\Z Matches at the end of the string or just before a newline at the end of the string
\G Matches at the starting offset character position, as passed to the preg_match() function

Note: It's important to note that an anchor doesn't itself match any characters; it merely ensures that the pattern appears at a specified point in the target string.

\A and \z are similar to ^ and $. The difference is that ^ and $ will also match at the beginning and end of a line, respectively, if matching a multi-line string in multi-line mode  \A and \z only match at the beginning and end of the target string, respectively.

\Z is useful when reading lines from a file that may or may not have a newline character at the end.

\b and \B are handy when searching text for complete words:

echo preg_match( "/over/", "My hovercraft is full of eels" );       // Displays "1"
echo preg_match( "/\bover\b/", "My hovercraft is full of eels" );   // Displays "0"
echo preg_match( "/\bover\b/", "One flew over the cuckoo's nest" ); // Displays "1"

When using \b, the beginning or end of the string is also considered a word boundary:

echo preg_match( "/\bover\b/", "over and under" );  // Displays "1"

By using the \b anchor, along with alternatives within a subexpression, it's possible to enhance the earlier "date detection" example further, so that it matches only two- or four-digit years (and not three-digit years):

echo preg_match( "/\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)" .
"\/\d{1,2}\/(\d{2}|\d{4})\b/", "jul/15/2006" );  // Displays "1"

echo preg_match( "/\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)" .
"\/\d{1,2}\/(\d{2}|\d{4})\b/", "jul/15/206" );  // Displays "0"

The last part of the expression reads, "Match either two digits or four digits, followed by a word boundary (or the end of the string)":

(\d{2}|\d{4})\b

Friday, June 12, 2015

Installing wordpress in root as well as in subdirectory

We have a wordpress site which is runnung in root directory. Now we want to install same site with different database name in subdirectory for testing purpose.

STARTING POINT:
http://www.mywordpress.com   /var/www/
http://www.mywordpress.com/foldername   /var/www/foldername

Step 1:

Put same code in /var/www/foldername as in /var/www/ . Connect it with new database.

Step 2:

Change .htaccess file in /var/www/foldername as given below

# BEGIN WordPress

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /foldername/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /foldername/index.php [L]
</IfModule>

# END WordPress

At this point the configuration will not be working because the .htaccess directives at /var/www/.htaccess with be controlling all aspects of the URL so the directives at /var/www/foldername/.htaccess will have no bearing.

Step 3 :

The final step is to modify the default WordPress htaccess directives so that they will have control in for all variations of the URL.
Now change .htaccess file in /var/www as given below

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
Options +FollowSymLinks
RewriteRule ^/?foldername/$ /var/www/foldername/index.php [L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Step 4:

Now login to your http://www.mywordpress.com/foldername/wp-admin/ section. Go to Setting->Permalinks.

Choose Post name in common setting.

Now it will work in root as well in subdirectory.

Friday, June 5, 2015

Filters and hooks for modifying woocommerce

1. Add email recipient when order completed

function woo_extra_email_recipient($recipient, $object) {
    $recipient = $recipient . ', your@email.com';
    return $recipient; }

add_filter( 'woocommerce_email_recipient_customer_completed_order', 'woo_extra_email_recipient', 10, 2);

2.  Redirect add to cart button to checkout page

add_filter ('add_to_cart_redirect', 'redirect_to_checkout');

function redirect_to_checkout() {
    global $woocommerce;
    $checkout_url = $woocommerce->cart->get_checkout_url();
    return $checkout_url;

}

3. Add custom field to edit address page

function woo_add_edit_address_fields( $fields ) {
    $new_fields = array(
                'date_of_birth'     => array(
                'label'             => __( 'Date of birth', 'woocommerce' ),
                'required'          => false,
                'class'             => array( 'form-row' ),
            ),
        );      

    $fields = array_merge( $fields, $new_fields );    
    return $fields;  

}


add_filter( 'woocommerce_default_address_fields', 'woo_add_edit_address_fields' );

4. Change “from” email address

function woo_custom_wp_mail_from() {
        global $woocommerce;
        return html_entity_decode( 'your@email.com' );
}

add_filter( 'wp_mail_from', 'woo_custom_wp_mail_from', 99 );

5. Change shop page title

add_filter( 'woocommerce_page_title', 'woo_shop_page_title');

function woo_shop_page_title( $page_title ) {  

    if( 'Shop' == $page_title) {
        return "My new title";
    }

}

6. Rename a product tab

add_filter( 'woocommerce_product_tabs', 'woo_rename_tab', 98);

function woo_rename_tab($tabs) {
 $tabs['description']['title'] = 'More info';
 return $tabs;

}

7. Remove “Products” from breadcrumb

function woo_custom_filter_breadcrumbs_trail ( $trail ) {
  foreach ( $trail as $k => $v ) {
    if ( strtolower( strip_tags( $v ) ) == 'products' ) {
      unset( $trail[$k] );
      break;
    }
  }
  return $trail;

}

add_filter( 'woo_breadcrumbs_trail', 'woo_custom_filter_breadcrumbs_trail', 10 );

8. Empty cart

function my_empty_cart(){
    global $woocommerce;
    $woocommerce->cart->empty_cart();
}


add_action('init', 'my_empty_cart');

9. Change related products number

function woo_related_products_limit() {
  global $product;  

    $args = array(
        'post_type'             => 'product',
        'no_found_rows'         => 1,
        'posts_per_page'        => 6,
        'ignore_sticky_posts'   => 1,
        'orderby'               => $orderby,
        'post__in'              => $related,
        'post__not_in'          => array($product->id)
    );
    return $args;
}


add_filter( 'woocommerce_related_products_args', 'woo_related_products_limit' );

10. Remove breadcrumb

remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20);