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);