Tuesday, October 30, 2018

Wordpress create custom fields into Settings -> General

<?php
add_filter('admin_init', 'notification_start_date');
function notification_start_date() {
    register_setting('general', 'notification_start_date', 'esc_attr');
    add_settings_field('notification_start_date', '<label for="notification_start_date">' . __('Notification start date', 'notification_start_date') . '</label>', 'notification_start_date_html', 'general');
}
function notification_start_date_html() {
    $value = get_option('notification_start_date', '');
    echo '<input type="date" id="notification_start_date" name="notification_start_date" value="' . $value . '" />';
}




add_filter('admin_init', 'notification_end_date');
function notification_end_date() {
    register_setting('general', 'notification_end_date', 'esc_attr');
    add_settings_field('notification_end_date', '<label for="notification_end_date">' . __('Notification start date', 'notification_end_date') . '</label>', 'notification_end_date_html', 'general');
}
function notification_end_date_html() {
    $value = get_option('notification_end_date', '');
    echo '<input type="date" id="notification_end_date" name="notification_end_date" value="' . $value . '" />';
}



add_filter('admin_init', 'notification');
function notification() {
    register_setting('general', 'notification', 'esc_attr');
    add_settings_field('notification', '<label for="notification">' . __('Notification start date', 'notification') . '</label>', 'notification_html', 'general');
}
function notification_html() {
    $value = get_option('notification', '');
    echo '<input type="date" id="notification" name="notification" value="' . $value . '" />';
}
?>

Wordpress create post with categories

add_action( 'init', 'article_fn' );

function article_fn() {

register_post_type( 'article', array(

  'labels' => array(

    'name' => 'Article',

    'add_new_item' => 'Add new article',

    'add_new' => 'Add new article',

    'view_item' => 'View Article',

    'singular_name' => 'Article',

    'set_featured_image' => 'Set article featured image',

    'search_items' => 'Search Article',

    'menu_name' => 'All Articles',

    'name_admin_bar' => 'View all articles'

   ),

  'description' => 'Article which we will be discussing on this blog.',

  'public' => true,

  'taxonomies' => array( 'category' ),

  'menu_position' => 2,

  'supports' => array( 'title', 'editor', 'custom-fields','author','thumbnail','excerpt','trackbacks','comments','revisions','page-attributes','post-formats' )

));

}

Wordpress custom posttype

add_theme_support('post-thumbnails');
add_post_type_support( 'my_product', 'thumbnail' );   
function create_post_type() {
        register_post_type( 'my_product',
            array(
                'labels' => array(
                    'name' => __( 'Products' ),
                    'singular_name' => __( 'Product' )
                ),
                'public' => true,
                'has_archive' => true
            )
        );
    }
    add_action( 'init', 'create_post_type' );

Hide wordpress current version details on browser.

function dd_remove_wp_version_strings($src) {

        global $wp_version;

        parse_str(parse_url($src, PHP_URL_QUERY), $query);

        if (!empty($query['ver']) && $query['ver'] === $wp_version) {

            $src = remove_query_arg('ver', $src);

        }

        return $src;

    }

    add_filter('script_loader_src', 'dd_remove_wp_version_strings');

    add_filter('style_loader_src', 'dd_remove_wp_version_strings');

    function dd_remove_version() {

        return '';

    }

    add_filter('the_generator', 'dd_remove_version');

Wednesday, August 26, 2015

Htaccess rules to compress, speedup and setexpiry script time

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
</IfModule>

<IfModule expires_module>
    ExpiresActive on
    ExpiresByType text/plain "access plus 1 week"
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType text/javascript "access plus 1 week"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-javascript "access plus 1 week"
    ExpiresByType image/svg+xml "access plus 1 week"
    ExpiresByType image/gif "access plus 1 week"
    ExpiresByType image/png "access plus 1 week"
    ExpiresByType image/ico "access plus 1 week"
    ExpiresByType image/x-icon "access plus 1 week"
    ExpiresByType image/jpg "access plus 1 week"
    ExpiresByType image/jpe "access plus 1 week"
    ExpiresByType image/jpeg "access plus 1 week"
    ExpiresByType font/truetype "access plus 1 week"
    ExpiresByType application/x-font-ttf "access plus 1 week"
    ExpiresByType font/opentype "access plus 1 week"
    ExpiresByType application/x-font-otf "access plus 1 week"
    ExpiresByType application/font-woff "access plus 1 week"
    ExpiresByType application/vnd.ms-fontobject "access plus 1 week"
    ExpiresByType application/x-shockwave-flash "access plus 1 week"
    ExpiresByType application/x-httpd-php-source "access plus 1 week"
</IfModule>

Sunday, July 12, 2015

Wordpress Create article with Multiple categories,country,regions etc.

<?php
register_post_type('Article', array(
'labels' => array(
'name' => 'Articles',
'singular_name' => 'Article',
'add_new' => __( 'Add New' ),
'add_new_item' => __( 'Add new Article' ),
'view_item' => 'View Article',
'edit_item' => 'Edit Article',
   'new_item' => __('New Article'),
   'view_item' => __('View Article'),
   'search_items' => __('Search Article'),
   'not_found' =>  __('No Article found'),
   'not_found_in_trash' => __('No Article found in Trash'),
),
'public' => true,
'exclude_from_search' => false,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'_edit_link' =>  'post.php?post=%d',
'rewrite' => array(
"slug" => "article",
"with_front" => false,
),
'query_var' => true,
'supports' => array('title', 'editor', 'page-attributes'),
'menu_position' => 101
));

//Categories
register_taxonomy(
    'categories',
    array('article'),
        array(
        'hierarchical' => true,
        'labels' => array(
        'name' => _x( 'Categories', 'taxonomy general name' ),
        'singular_name' => _x( 'Category', 'taxonomy singular name' ),
        'search_items' =>  __( 'Search Category' ),
        'all_items' => __( 'All Categories' ),
        'parent_item' => __( 'Parent Category' ),
        'parent_item_colon' => __( 'Parent Category:' ),
        'edit_item' => __( 'Edit Category' ),
        'update_item' => __( 'Update Category' ),
        'add_new_item' => __( 'Add New Category' ),
        'new_item_name' => __( 'New Category Name' ),
        'menu_name' => __( 'Category' ),
    ),
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => array(
"slug" => "category",
"with_front" => false,
),
));

//Countries
register_taxonomy(
    'country',
    array('article'),
        array(
        'hierarchical' => true,
        'labels' => array(
        'name' => _x( 'Countries', 'taxonomy general name' ),
        'singular_name' => _x( 'Country', 'taxonomy singular name' ),
        'search_items' =>  __( 'Search Countries' ),
        'all_items' => __( 'All Countries' ),
        'parent_item' => __( 'Parent Country' ),
        'parent_item_colon' => __( 'Parent Country:' ),
        'edit_item' => __( 'Edit Country' ),
        'update_item' => __( 'Update Country' ),
        'add_new_item' => __( 'Add New Country' ),
        'new_item_name' => __( 'New Country Name' ),
        'menu_name' => __( 'Countries' ),
    ),
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => array(
"slug" => "country",
"with_front" => false,
),
));

//Regions
register_taxonomy(
    'region',
    array('article'),
        array(
        'hierarchical' => true,
        'labels' => array(
        'name' => _x( 'Regions', 'taxonomy general name' ),
        'singular_name' => _x( 'Region', 'taxonomy singular name' ),
        'search_items' =>  __( 'Search Regions' ),
        'all_items' => __( 'All Regions' ),
        'parent_item' => __( 'Parent Region' ),
        'parent_item_colon' => __( 'Parent Region:' ),
        'edit_item' => __( 'Edit Region' ),
        'update_item' => __( 'Update Region' ),
        'add_new_item' => __( 'Add New Region' ),
        'new_item_name' => __( 'New Region Name' ),
        'menu_name' => __( 'Regions' ),
    ),
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => array(
"slug" => "region",
"with_front" => false,
),
));
?>

Wordpress create menu and submenu on admin side.

function admin_left_panel() {
    add_menu_page('Page Title', 'Left menu label', 'manage_options','pageurl1', 'menu_one');
    add_submenu_page('pageurl1', 'Page Title','Left menu label 2', 'manage_options', 'pageurl2','menu_two');
    add_submenu_page('pageurl1', 'Page Title','Left menu label 3','manage_options', 'pageurl3', 'menu_three');
}

add_action('admin_menu', 'admin_left_panel');

function menu_one() {
    echo '<div class="wrap"><div id="icon-options-general" class="icon32"><br></div><h2>Page 1</h2></div>';
}

function menu_two() {
    echo '<div class="wrap"><div id="icon-options-general" class="icon32"><br></div><h2>Page 2</h2></div>';
}

function menu_three() {
    echo '<div class="wrap"><div id="icon-options-general" class="icon32"><br></div><h2>Page 3</h2></div>';
}

Sunday, July 5, 2015

Wordpress custom query

<?php
$args_fp = array(
    'post_type' => 'page',
    'post__in' => array(10,11,12,13),
    'orderby' => 'post__in',
);
$fp_query = null;
$fp_query = new WP_Query($args_fp);
while ($fp_query->have_posts()) : $fp_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?><?php the_content(); ?></a></li>
<?php endwhile; ?>
?>

Sunday, May 31, 2015

wordpress plugin for create custom category type and post type

<?php
/*
Plugin Name: MK custom texonomy and post type
Plugin URI: https://www.google.com/
Description: Admin can create its custom category and posts and view on frontend side.
Author: Mayank Patel
Version: 1.0.8
Author URI: http://www.google.com/
Text Domain: cpt-plugin
Domain Path: /languages
License: GPLv2
*/

function my_custom_post_article() {
  $args = array();
  register_post_type( 'article', $args );
}
add_action( 'init', 'my_custom_post_article' );

function my_custom_post_articles() {
  $labels = array(
    'name'               => _x( 'Articles', 'post type general name' ),
    'singular_name'      => _x( 'Article', 'post type singular name' ),
    'add_new'            => _x( 'Add New', 'book' ),
    'add_new_item'       => __( 'Add New Article' ),
    'edit_item'          => __( 'Edit Article' ),
    'new_item'           => __( 'New Article' ),
    'all_items'          => __( 'All Articles' ),
    'view_item'          => __( 'View Article' ),
    'search_items'       => __( 'Search Articles' ),
    'not_found'          => __( 'No article found' ),
    'not_found_in_trash' => __( 'No article found in the Trash' ),
    'parent_item_colon'  => '',
    'menu_name'          => 'Article'
  );
  $args = array(
    'labels'        => $labels,
    'description'   => 'Holds our article and article specific data',
    'public'        => true,
    'menu_position' => 5,
   'supports'      => array( 'title','author', 'editor','thumbnail','trackbacks' ,'excerpt','comments' ,'custom-fields','revisions','page-attributes','post-formats'),
    'has_archive'   => true,
  );
  register_post_type( 'article', $args );
}
add_action( 'init', 'my_custom_post_articles' );


function my_updated_messages( $messages )
{
  global $post, $post_ID;
  $messages['article'] = array(
    0 => '',
    1 => sprintf( __('Article updated. <a href="%s">View article</a>'), esc_url( get_permalink($post_ID) ) ),
    2 => __('Custom field updated.'),
    3 => __('Custom field deleted.'),
    4 => __('Article updated.'),
    5 => isset($_GET['revision']) ? sprintf( __('Article restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
    6 => sprintf( __('Article published. <a href="%s">View article</a>'), esc_url( get_permalink($post_ID) ) ),
    7 => __('Article saved.'),
    8 => sprintf( __('Article submitted. <a target="_blank" href="%s">Preview article</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
    9 => sprintf( __('Article scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview article</a>'), date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
    10 => sprintf( __('Article draft updated. <a target="_blank" href="%s">Preview article</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
  );
  return $messages;
}
add_filter( 'post_updated_messages', 'my_updated_messages' );

function my_taxonomies_article()
{
 // Hirarchical false = tags and true = categories
 register_taxonomy("article_category", array("article"), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Article", "rewrite" => true));
 register_taxonomy("article_tags", array("article"), array("hierarchical" => false, "label" => "Tags", "singular_label" => "tags", "rewrite" => true));
}

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

Wordpress to display query post lists arguments on frontend side.

$args = array(
'category__and' => array(1,3), // finding categories 1 & 3
'posts_per_page' => 10,
//'posts_per_page' => -1 , // fetch all posts from db
'year' => 2015,
'monthnum' => 05,
'orderby' => 'title',
'post_type' => 'post',
'category_name' => 'my-category-slug', // finding only current slug category posts
'order' => 'DESC'
);


//Starting with version 4.1, meta_query clauses can be nested in order to construct complex queries. For example, "show me productss where color=orange OR color=red&size=small" translates to the following:
$args = array(
'post_type'  => 'product',
'meta_query' => array(
'relation' => 'OR',
array(
'key'     => 'color',
'value'   => 'orange',
'compare' => '=',
),
                array(
                        'relation' => 'AND',
                        array(
                                'key' => 'color',
                                'value' => 'red',
                                'compare' => '=',
                        ),
                        array(
                                'key' => 'size',
                                'value' => 'small',
                                'compare' => '=',
                        ),
),
),
);
$query = new WP_Query( $args );






$args = array(
'post_type'  => 'my_custom_post_type',
'meta_key'   => 'age',
'orderby'    => 'meta_value_num',
'order'      => 'ASC',
'meta_query' => array(
array(
'key'     => 'age',
'value'   => array( 3, 4 ),
'compare' => 'IN',
),
),
);
$query = new WP_Query( $args );

//Return posts between 9AM to 5PM on weekdays
$args = array(
'date_query' => array(
array(
'hour'      => 9,
'compare'   => '>=',
),
array(
'hour'      => 17,
'compare'   => '<=',
),
array(
'dayofweek' => array( 2, 6 ),
'compare'   => 'BETWEEN',
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );






$paged = ( isset( $_GET['pg'] ) && intval( $_GET['pg'] ) > 0 )? intval( $_GET['pg'] ) : 1;
$query_args = array(
'post_type' => 'post',
'paged' => $paged,
'posts_per_page' => 1
);
query_posts( $query_args );

how to get Wordpress current user and user id?

$current_user = wp_get_current_user();
$current_user_name = $current_user->user_login ;

$user_id = get_current_user_id();

How to create custom registration page on frontend side in wordpress?

1) On index.php below get_header();

<?php
            if(!is_user_logged_in())
{
    ?>
    <script>window.location.href = '<?php echo home_url()."/login";?>';</script>
    <?php
    //wp_redirect(home_url()."/login");
}   
?>

2)Create file name "custom-register.php" and paste the following
<?php
/**
 * Template Name: Register Page
 *
 */
get_header();
?>
<?php
function registrationForm() {

            require_once(ABSPATH . WPINC . '/registration.php');
            global $wpdb, $user_ID;
            //Check whether the user is already logged in
            if ($user_ID)
            {
                header( 'Location:' . home_url());
            }
            else
            {
                $errors = array();

                if( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['signup'])) {
           
                    // Check username is present and not already in use
                    $username = $wpdb->escape($_REQUEST['username']);
                    if ( strpos($username, ' ') !== false ) {
                        $errors[] = "Sorry, no spaces allowed in usernames";
                    }
                    if(empty($username)) {
                        $errors[] = "Please enter a username";
                    } elseif( username_exists( $username ) ) {
                        $errors[] = "Username already exists, please try another";
                    }
           
                    // Check email address is present and valid
                    $email = $wpdb->escape($_REQUEST['email']);
                    if( !is_email( $email ) ) {
                        $errors[] = "Please enter a valid email";
                    } elseif( email_exists( $email ) ) {
                        $errors[] = "This email address is already in use";
                    }
           
                    // Check password is valid
                    if(0 === preg_match("/.{6,}/", $_POST['password'])){
                      $errors[] = "Password must be at least six characters";
                    }
                   
                    if(0 === count($errors)) {
           
                        $password = $_POST['password'];
                        
                         $new_user_id = wp_create_user( $username, $password, $email );
                       
                        global $wpdb;
                           $url = home_url();
                            $to = $email;
                            $subject = "New Account Verification";

                            $header .= "Reply-To: <test@test.org>\r\n";
                                                        $header .= "Return-Path: <testteam@test.org>\r\n";
                            $headers = "From: ePray Team <test@test.org> \r\n";
                                                        $header .= "Organization: Test.org\r\n";
                            $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
                                                   
                            $message = "
                                    <b>Dear ".ucwords($username).",<br /><br />Thank you for registering on Test!</b><br /><b>Email : $email</b><br /><br />
                                    But before we can activate your account, one last step must be taken to complete your registration.
                                    Please note, you must complete this last step to become a registered member. You will only need to visit this URL once to activate your account.
                                    To complete your registration, please visit this URL:<br />
                                     After verification : <a href='$url'>Sign in</a><br />
                                    To sign up for our newsletter click <a href='$url/newsletter'>here</a><br /><br />
                                    <b>Best Regards,<br />
                                     Test Team</b>";

                        $res = wp_mail($to, $subject, $message, $headers);
                        $success = 1;
                        $user_id = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."users WHERE user_login = '$username' ",ARRAY_A);
                       
                        $secure_cookie = is_ssl() ? true : false;
                        wp_set_auth_cookie( $user_id['ID'], true, $secure_cookie );
                        //wp_safe_redirect(home_url());
                        ?>
                        <script>window.location.href='<?php echo home_url();?>';</script>
                        <script>
                            message('<?php echo json_encode($errors);?>');
                        </script>
                        <?php
           
                    }
                    else {
                        ?>
                            <script>
                                message('<?php echo json_encode($errors);?>');
                            </script>
                        <?php
                    }
           
                }

            }
        ?>
       
        <div class="signup-form">
                    <form method="post" action="#" id="RegisterForm">
                        <ul>
                            <li>
                                <input type="text" value="" class="text-bx" placeholder="Username" name="username" maxlength="20" autocomplete="off" />
                            </li>
                            <li>
                                <input type="email" value="" class="text-bx" placeholder="Email" name="email" maxlength="60" autocomplete="off" />
                            </li>
                            <li>
                                <input type="password" value="" class="text-bx" placeholder="Password" name="password" maxlength="30" autocomplete="off" />
                            </li>
                            <li>
                                <input type="checkbox" name="terms" id="terms" class="check" /><p>By creating your account you confirm that youve read
                                and accepted the <a href="#terms-content" class="fancybox accpt_te">Terms of Service.</a></p>
                                <input type="submit" name="signup" value="Sign-up for ePray" class="sgn-up" />
                            </li>
                        </ul>
                    </form>
                </div>
           
       
<?php
}
//add_shortcode('mk_registration', 'registrationForm');
registrationForm();
get_footer();
?>

3) Create backend page name "Register", Select template "Custom Register" and publish page.

How to create custom login page on frontend side in wordpress?

1) On index.php below get_header();

<?php
            if(!is_user_logged_in())
{
    ?>
    <script>window.location.href = '<?php echo home_url()."/login";?>';</script>
    <?php
    //wp_redirect(home_url()."/login");
}   
?>

2)Create file name "custom-login.php" and paste the following

<?php
/*
Template Name: Custom Login
*/
get_header();   
    if(isset($_POST["wp-submit"]))
    {
        $args = array(
        'echo' => true,
        'redirect' => site_url( $_SERVER['REQUEST_URI'] ),
        'form_id' => 'loginform',
        'label_username' => __( 'Username' ),
        'label_password' => __( 'Password' ),
        'label_remember' => __( 'Remember Me' ),
        'label_log_in' => __( 'Log In' ),
        'id_username' => 'user_login',
        'id_password' => 'user_pass',
        'id_remember' => 'rememberme',
        'id_submit' => 'wp-submit',
        'remember' => true,
        'value_username' => NULL,
        'value_remember' => false );
        $args = array('redirect' => get_permalink( get_page( $page_id_of_member_area ) ) );
    }
   
    if(is_user_logged_in())
    {
    ?>
        <script>window.location.href = '<?php echo home_url();?>';</script>
    <?php
    }
    else
    {
        wp_login_form( $args );
    }
get_footer();
?>

3) Create backend page name "Login", Select template "Custom Login" and publish page.

how to create custom post type with category in Wordpress?


function my_custom_post_product() {
  $args = array();
  register_post_type( 'product', $args );
}
add_action( 'init', 'my_custom_post_product' );

function my_custom_post_products() {
  $labels = array(
    'name'               => _x( 'Products', 'post type general name' ),
    'singular_name'      => _x( 'Product', 'post type singular name' ),
    'add_new'            => _x( 'Add New', 'book' ),
    'add_new_item'       => __( 'Add New Product' ),
    'edit_item'          => __( 'Edit Product' ),
    'new_item'           => __( 'New Product' ),
    'all_items'          => __( 'All Products' ),
    'view_item'          => __( 'View Product' ),
    'search_items'       => __( 'Search Products' ),
    'not_found'          => __( 'No products found' ),
    'not_found_in_trash' => __( 'No products found in the Trash' ),
    'parent_item_colon'  => '',
    'menu_name'          => 'Products'
  );
  $args = array(
    'labels'        => $labels,
    'description'   => 'Holds our products and product specific data',
    'public'        => true,
    'menu_position' => 5,
   'supports'      => array( 'title','author', 'editor','thumbnail','trackbacks' ,'excerpt','comments' ,'custom-fields','revisions','page-attributes','post-formats'),
    'has_archive'   => true,
  );
  register_post_type( 'product', $args );
}
add_action( 'init', 'my_custom_post_products' );


function my_updated_messages( $messages )
{
  global $post, $post_ID;
  $messages['product'] = array(
    0 => '',
    1 => sprintf( __('Product updated. <a href="%s">View product</a>'), esc_url( get_permalink($post_ID) ) ),
    2 => __('Custom field updated.'),
    3 => __('Custom field deleted.'),
    4 => __('Product updated.'),
    5 => isset($_GET['revision']) ? sprintf( __('Product restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
    6 => sprintf( __('Product published. <a href="%s">View product</a>'), esc_url( get_permalink($post_ID) ) ),
    7 => __('Product saved.'),
    8 => sprintf( __('Product submitted. <a target="_blank" href="%s">Preview product</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
    9 => sprintf( __('Product scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview product</a>'), date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
    10 => sprintf( __('Product draft updated. <a target="_blank" href="%s">Preview product</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
  );
  return $messages;
}
add_filter( 'post_updated_messages', 'my_updated_messages' );

function my_taxonomies_product()
{
// Hirarchical false = tags and true = categories
register_taxonomy("product_category", array("product"), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Product", "rewrite" => true));
register_taxonomy("product_tags", array("product"), array("hierarchical" => false, "label" => "Tags", "singular_label" => "tags", "rewrite" => true));
}

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

Wordpress create url with custom params and custom template

1) Place following on functions.php file

function add_rewrite_rules($aRules) {
    $aNewRules = array('newcustomtemplatepage/([^/]+)/?$' => 'index.php?pagename=newcustomtemplatepage&user=$matches[1]');
    $aRules = $aNewRules + $aRules;
    return $aRules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');

2) Save paramalinks on backend side (Settings -> Permalinks -> Save Changes)

Wordpress custom photo gallery with custom post type


//----------------------------------------------
//--------------add theme support for thumbnails
//----------------------------------------------
if ( function_exists( 'add_theme_support')){
add_theme_support( 'post-thumbnails' );
}
add_image_size( 'admin-list-thumb', 80, 80, true); //admin thumbnail

//----------------------------------------------
//----------register and label gallery post type
//----------------------------------------------
$gallery_labels = array(
    'name' => _x('Gallery', 'post type general name'),
    'singular_name' => _x('Gallery', 'post type singular name'),
    'add_new' => _x('Add New', 'gallery'),
    'add_new_item' => __("Add New Gallery"),
    'edit_item' => __("Edit Gallery"),
    'new_item' => __("New Gallery"),
    'view_item' => __("View Gallery"),
    'search_items' => __("Search Gallery"),
    'not_found' =>  __('No galleries found'),
    'not_found_in_trash' => __('No galleries found in Trash'),
    'parent_item_colon' => ''
     
);
$gallery_args = array(
    'labels' => $gallery_labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => true,
    'hierarchical' => false,
    'menu_position' => null,
    'capability_type' => 'post',
    'supports' => array('title', 'excerpt', 'editor', 'thumbnail'),
    'menu_icon' => get_bloginfo('template_directory') . '/images/photo-album.png' //16x16 png if you want an icon
);
register_post_type('gallery', $gallery_args);


//----------------------------------------------
//------------------------create custom taxonomy
//----------------------------------------------
add_action( 'init', 'jss_create_gallery_taxonomies', 0);

function jss_create_gallery_taxonomies(){
    register_taxonomy(
        'phototype', 'gallery',
        array(
            'hierarchical'=> true,
            'label' => 'Photo Types',
            'singular_label' => 'Photo Type',
            'rewrite' => true
        )
    );  
}

//----------------------------------------------
//--------------------------admin custom columns
//----------------------------------------------
//admin_init
add_action('manage_posts_custom_column', 'jss_custom_columns');
add_filter('manage_edit-gallery_columns', 'jss_add_new_gallery_columns');

function jss_add_new_gallery_columns( $columns ){
    $columns = array(
        'cb'                =>        '<input type="checkbox">',
        'jss_post_thumb'    =>        'Thumbnail',
        'title'                =>        'Photo Title',
        'phototype'            =>        'Photo Type',
        'author'            =>        'Author',
        'date'                =>        'Date'
     
    );
    return $columns;
}

function jss_custom_columns( $column ){
    global $post;
 
    switch ($column) {
        case 'jss_post_thumb' : echo the_post_thumbnail('admin-list-thumb'); break;
        case 'description' : the_excerpt(); break;
        case 'phototype' : echo get_the_term_list( $post->ID, 'phototype', '', ', ',''); break;
    }
}

//add thumbnail images to column
add_filter('manage_posts_columns', 'jss_add_post_thumbnail_column', 5);
add_filter('manage_pages_columns', 'jss_add_post_thumbnail_column', 5);
add_filter('manage_custom_post_columns', 'jss_add_post_thumbnail_column', 5);

// Add the column
function jss_add_post_thumbnail_column($cols){
    $cols['jss_post_thumb'] = __('Thumbnail');
    return $cols;
}

function jss_display_post_thumbnail_column($col, $id){
  switch($col){
    case 'jss_post_thumb':
      if( function_exists('the_post_thumbnail') )
        echo the_post_thumbnail( 'admin-list-thumb' );
      else
        echo 'Not supported in this theme';
      break;
  }
}

How to implement ajax in wordpress?

index.php

1)
<a onclick="fnRequest()">Test Request</a>
<a id="response_text"></a>


2)
<script type="text/javascript">
function fnRequest()
{
    var data = {};
    data.register_email = "test";
    data.action = "request_action";
    jQuery.post('<?php echo rawurldecode(esc_url(home_url( '/'))); ?>wp-admin/admin-ajax.php',data, responsefunction);
}
function responsefunction(result)
{
    $("#response_text").html(result);
    //alert(result);
}
</script>


3)
functions.php

add_action('wp_ajax_request_action', 'request_action');
add_action('wp_ajax_nopriv_request_action' , 'request_action');
function request_action()
{
    echo "Testing response";
}

Sunday, March 29, 2015

wordpress Create new custom page like posts page on backend side


add_action('init', 'article_register');

function article_register() {

$labels = array(
'name' => _x('Articles', 'post type general name'),
'singular_name' => _x('Article Item', 'post type singular name'),
'add_new' => _x('Add New', 'Article item'),
'add_new_item' => __('Add New Article Item'),
'edit_item' => __('Edit Article Item'),
'new_item' => __('New Article Item'),
'view_item' => __('View Article Item'),
'search_items' => __('Search Article'),
'not_found' =>  __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => ''
);

$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'menu_icon' => get_stylesheet_directory_uri() . '/article16.png',
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','thumbnail')
 );

register_post_type( 'article' , $args );
}
register_taxonomy("Skills", array("article"), array("hierarchical" => true, "label" => "Skills", "singular_label" => "Skill", "rewrite" => true));

Wordpress create custom page with (Next & Previous) Pagination.


1) Create a page on theme folder name "custom2.php"
2) Paste following code into custom2.php file

<?php
/*
Template Name: Custom Query category page.
*/
?>
<?php get_header(); ?>
<h3>Recent Articles</h3><br />
<ul>
<?php
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query('showposts=2&cat=1'.'&paged='.$paged);
?>
<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<div class="navigation">
  <div class="alignleft"><?php previous_posts_link('&laquo; Previous') ?></div>
  <div class="alignright"><?php next_posts_link('Next &raquo;') ?></div>
</div>
<?php $wp_query = null; $wp_query = $temp;?>
<?php get_footer(); ?>


3) Create one page on backend side and select template "Custom Query category page".
That's it.

Wordpress display post by category on custom page template.


1) Create a page on theme folder name "custom.php"
2) Paste following code into custom.php file



<?php
/*
Template Name: Custom category page.
*/
?>

<?php get_header(); ?>

<h2>Post of category "Uncategorized"</h2><br />

<?php

function custom_pagination($numpages = '', $pagerange = '', $paged='') {

  if (empty($pagerange)) {
    $pagerange = 2;
  }

  /**
   * This first part of our function is a fallback
   * for custom pagination inside a regular loop that
   * uses the global $paged and global $wp_query variables.
   *
   * It's good because we can now override default pagination
   * in our theme, and use this function in default quries
   * and custom queries.
   */
  global $paged;
  if (empty($paged)) {
    $paged = 1;
  }
  if ($numpages == '') {
    global $wp_query;
    $numpages = $wp_query->max_num_pages;
    if(!$numpages) {
        $numpages = 1;
    }
  }

  /**
   * We construct the pagination arguments to enter into our paginate_links
   * function.
   */
  $pagination_args = array(
    'base'            => get_pagenum_link(1) . '%_%',
    'format'          => 'page/%#%',
    'total'           => $numpages,
    'current'         => $paged,
    'show_all'        => False,
    'end_size'        => 1,
    'mid_size'        => $pagerange,
    'prev_next'       => True,
    'prev_text'       => __('&laquo;'),
    'next_text'       => __('&raquo;'),
    'type'            => 'plain',
    'add_args'        => false,
    'add_fragment'    => ''
  );

  $paginate_links = paginate_links($pagination_args);

  if ($paginate_links) {
    echo "<nav class='custom-pagination'>";
      echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> ";
      echo $paginate_links;
    echo "</nav>";
  }

}


  $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

  $custom_args = array(
      'post_type' => 'post',
      'posts_per_page' => 2,
      'paged' => $paged
    );

  $custom_query = new WP_Query( $custom_args ); ?>

  <?php if ( $custom_query->have_posts() ) : ?>
 
    <!-- the loop -->
    <?php while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
      <article class="loop">
        <h3><?php the_title(); ?></h3>
        <div class="content">
          Excerpt : <?php the_excerpt(); ?><br />
 Content : <?php the_content(); ?><br />
 Link Page : <?php wp_link_pages(); ?><br />
 ID : <?php the_ID();?><br />
 Category : <?php the_category( $separator, $parents, $post_id ); ?> <br />
 Category Description : <?php category_description();?><br />
 Tags : <?php the_tags();?><br />
 Meta : <?php the_meta();?><br />
 Author : <?php the_author_posts_link(); ?> <?php //echo get_the_modified_author(); ?> : <?php //the_author(); ?>: <?php //echo get_the_author_posts(); ?><br />
 Last modified: <?php the_modified_date('F j, Y'); ?><br />
 Created on : <?php echo get_the_date( 'Y-m-d' ); ?><br />
 Published time : <?php the_time( 'H:i:s' ); ?><br />
        </div>
      </article>
    <?php endwhile; ?>
    <!-- end of the loop -->

    <!-- pagination here -->
    <?php
      if (function_exists(custom_pagination)) {
        custom_pagination($custom_query->max_num_pages,"",$paged);
      }
    ?>
<?php wp_reset_postdata(); ?>
<?php else:  ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

<?php
get_footer();
?>


3) Create one page on backend side and select template "Custom category page".

Thats it.