Sunday, May 31, 2015

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.

Create post programatically and assigned category to posts (If category & Posts not exists it will create and assign to that posts).


$new_post = array(
'post_name' => sanitize_title($data['Handle']), // Slug
'post_title' => convert_chars($data['Title']),
'post_content' => wpautop(convert_chars($data['Body (HTML)'])),
'post_status' => 'publish',
'post_type' => 'post',
//'post_category' => array($new_cat_ID)
);

if($id = post_exists($new_post['post_title'], $new_post['post_content']))
{
$new_post['ID'] = (int)$id;
$id = wp_update_post($new_post);
if ( is_wp_error( $id ) )
{
return $id;
}
if (!$id)
{
$output .= "Couldn't get post ID";
return;
}

foreach($data as $key => $value)
{
update_post_meta($id, sanitize_user('Shopify '.$key), esc_attr($value));
}
$output .= 'Updated !'. ' <a href="'.get_permalink($id).'">View '.$data['Title'].'</a>';
}
else
{
$id = wp_insert_post($new_post);
}

$arrCategories = explode(',', $data['Categories']);
if(count($arrCategories) > 0)
{
global $wpdb;
foreach($arrCategories as $key => $category_name)
{
$slug = strtolower( str_ireplace( ' ', '-', $category_name ) );
$sqlTermQuery = "SELECT * FROM wp_terms WHERE slug = '".$slug."'";
$arrTermsArray = $wpdb->get_results($sqlTermQuery);
if(count($arrTermsArray) <= 0)
{
$sqlInsertTerm = "INSERT INTO wp_terms SET name = '".ucfirst($category_name)."',slug = '".$slug."'";
$wpdb->query($sqlInsertTerm);
$lastid = $wpdb->insert_id;
$sqlInsertTermTexonomy = "INSERT INTO wp_term_taxonomy SET term_id = '".$lastid."',taxonomy = 'category'";
$arrTexonomy[] = $wpdb->get_results($sqlInsertTermTexonomy);
$lasttexonomyid = $wpdb->insert_id;
$arrCategories_ids[] = $lastid;
}
else
{
$sqlTermQuery = "SELECT * FROM wp_terms WHERE slug = '".$slug."'";
$arrTermsArray = $wpdb->get_results($sqlTermQuery);
$intTermid = $arrTermsArray[0]->term_id;

$sqlTexonomy = "SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE term_id = '".$intTermid."' AND taxonomy = 'download_category'";
$arrTaxonomy = $wpdb->get_results($sqlTexonomy);
if(count($arrTaxonomy) > 0)
{
$lasttexonomyid = $arrTaxonomy[0]->term_taxonomy_id;
}
else
{
$sqlInsertTermTexonomy = "INSERT INTO wp_term_taxonomy SET term_id = '".$intTermid."',taxonomy = 'download_category'";
$arrTexonomy[] = $wpdb->get_results($sqlInsertTermTexonomy);
$lasttexonomyid = $wpdb->insert_id;
}
}

if($lasttexonomyid >0 && $id > 0)
{
$sqlInsertTerm = "INSERT INTO wp_term_relationships SET object_id = '".$id."',term_taxonomy_id = '".$lasttexonomyid."'";
$wpdb->query($sqlInsertTerm);
}
}
}

Sunday, February 2, 2014

JQuery image preview on hover and onclick

Sorry, no attachments exist.
JQuery image preview on hover and onclick

Image-preview


JQuery image preview on hover and onclick

Disabling local modules in Magento.

if you ever wanted to temporarily disable all local modules, here is how to.

Open file app/etc/local.xml

Locate the tag

Change it’s value to true.

i.e

<disable_local_modules>false</disable_local_modules>


Disabling local modules in Magento.

Thursday, January 30, 2014

Sunday, January 26, 2014

Wordpress Banner Slider By Mayank Patel

Sorry, no attachments exist.
WordPress banner Slider by mayank patel


Wordpress Banner Slider By Mayank Patel

PHP Script

<?php

function getBrowser()

a-zA-Z.]*)#’;

if (!preg_match_all($pattern, $u_agent, $matches))


// we have no matching number just continue

// See how many we have.

$i = count($matches['browser']);

if ($i != 1)


//we will have two since we are not using ‘other’ argument yet

//see if version is before or after the name

if (strripos($u_agent,”Version”) < strripos($u_agent,$ub))


$version= $matches['version'][0];


else


$version= $matches['version'][1];



else


$version= $matches['version'][0];

// Check if we have a number.

if($version==null

// Now try it.

$ua=getBrowser();

$yourbrowser= “Your browser = ” . $ua['name'] . “<br />Version = ” . $ua['version'] . ” <br />” .”O.S. = “. $ua['platform'] . ” <br />reports = ” . $ua['userAgent'];

print_r($yourbrowser);

?>


PHP Script

Sunday, December 29, 2013

Wordpress Banner Slider (Backend Side)

Sorry, no attachments exist.
WordPress banner Slider by mayank patel


Wordpress Banner Slider (Backend Side)

Saturday, December 14, 2013

Sunday, December 8, 2013

Wordpress change email from wordpress@domain.com to custom email address

function change_from_email_name()


$message = get_option(‘blogname’);

return $message;


add_filter(‘wp_mail_from_name’, ‘change_from_email_name’); // // changes email from default “wordpress@yourdomain.com”//

function change_from_email()


$message = get_option(‘admin_email’);

return $message;


add_filter(‘wp_mail_from’, ‘change_from_email’); /// Changed by mayank patel over ////


Wordpress change email from wordpress@domain.com to custom email address

Wordpress change registration email from wordpress@domainname.com to custom email.

On function.php file of current theme place follownig code at last

function change_from_email_name()

$message = get_option(‘blogname’);

return $message;


add_filter(‘wp_mail_from_name’, ‘change_from_email_name’);

//

// changes email from default “wordpress@yourdomain.com”

//

function change_from_email()

$message = get_option(‘admin_email’);

return $message;


add_filter(‘wp_mail_from’, ‘change_from_email’);


Wordpress change registration email from wordpress@domainname.com to custom email.

Sunday, December 1, 2013

Magento print query for throughout site.

Lib/zend/Db/Adapter/Abstract.php

find :

public function query($sql, $bind = array())


after :

$sql = $sql->assemble();

//echo $sql . “\n<br />\n”;

// var_dump($bind);


Magento print query for throughout site.

Magento extension for facebook comments from product detail page.

Sorry, no attachments exist.

Magento extension for facebook comments from product detail page.


Magento extension for facebook comments from product detail page.

Magento customer credit extension.

Sorry, no attachments exist.

Magento customer credit extension.


Magento customer credit extension.