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.

Thursday, November 28, 2013

Magento blacklist email address extension

Sorry, no attachments exist.

Magento blacklist email address extension



Magento blacklist email address extension

Magento extension for one page easy checkout

Sorry, no attachments exist.

Magento extension for one page easy checkout



Magento extension for one page easy checkout

Magento improve one page checkout with designing (css only)

Sorry, no attachments exist.

Magento improve one page checkout with designing (css only)



Magento improve one page checkout with designing (css only)

Magento Google analytics extension

Sorry, no attachments exist.

Magento Google analytics extension



Magento Google analytics extension

Magento comments on checkout extension

Sorry, no attachments exist.

Magento comments on checkout extension



Magento comments on checkout extension

Magento developer toolbar extension

Sorry, no attachments exist.

Magento developer toolbar extension



Magento developer toolbar extension

Magento facebook likebox and connect extension.

Sorry, no attachments exist.

Magento facebook likebox and connect extension.



Magento facebook likebox and connect extension.

Wordpress Extension for Album and image gallery

Sorry, no attachments exist.

Wordpress Extension for Album and image gallery


Wordpress Extension for Album and image gallery

Wordpress Extension BackUpWordPress files and databases

Sorry, no attachments exist.

Simple automated back ups of your WordPress powered website.

Wordpress Extension BackUpWordPress files and databases



Wordpress Extension BackUpWordPress files and databases

Wordpress Extension for page navigation (pageination display format)

Sorry, no attachments exist.

Wordpress Extension for page navigation (pageination display format)



Wordpress Extension for page navigation (pageination display format)

Wordpress Extension for maintanance mode

Sorry, no attachments exist.

Wordpress Extension for maintanance mode



Wordpress Extension for maintanance mode

Magento Video Gallery Extensions

Sorry, no attachments exist.

Magento Video Gallery Extensions)



Magento Video Gallery Extensions

Steps to Move WordPress From Local Server to Live Site

Step 1: Export Local WordPress Database

Step 2: Uploading WordPress Files to Live Site

Step 3: Creating MySQL Database on Live Site

Step 4: Importing WordPress Database on Live Site

Step 5: Changing the Site URL (on wp_options table see siteurl option , update it),(on wp_options table see home option , update it)

Step 6: Setting Up your Live Site

Step 7: Fixing Images and Broken Links by updating Paths

UPDATE wp_posts SET post_content = REPLACE(post_content, ‘localhost/test/’, ‘www.yourlivesite.com’);



Steps to Move WordPress From Local Server to Live Site

How to Enable and Disable Automatic Updates in WordPress for Major Releases

define( ‘WP_AUTO_UPDATE_CORE’, true );


There is one little problem with this code. It also enables development or nightly updates. To disable nightly builds and development updates you need to add this code in a site-specific plugin or in your theme’s functions.php file.


add_filter( ‘allow_dev_auto_core_updates’, ‘__return_false’ );


This filter will disable automatic updates for nightly builds or development updates.



How to Enable and Disable Automatic Updates in WordPress for Major Releases

WordPress blank page issue

Solution 1 – Check your plugin settings


SELECT option_value FROM wp_options WHERE option_name = ‘active_plugins’

UPDATE wp_options SET option_value = ” WHERE option_name = ‘active_plugins’


Solution 2 – Check your template settings


SELECT option_name, option_value FROM wp_options WHERE option_name IN (‘template’, ‘stylesheet’)

UPDATE wp_options SET option_value = ‘default’ WHERE option_name IN (‘stylesheet’, ‘template’)


Solution 3 – Check the “key” files


There are two “key” files, wp-config.php and .htaccess, that you need to check.


If you can’t access either the WordPress homepage or the admin page, check the wp-config.php file and make sure that there is no empty lines or other characters after “?>”.


If you have a .htaccess file in your WordPress folder, rename the .htaccess file to see if it rectifies the blank page issue. If so, you’ll need to review the settings in the .htaccess file.


 


Solution 4 – Enable error display

php_flag display_errors on


 



WordPress blank page issue

Add Google Analytics

Simply paste the code below and insert your Google Analytics where it says paste your Google Analytics. You can paste the code once in your functions.php file and never have to worry about it again. We are adding an action to the wp_footer, so it will automatically insert adsense codes wherever on all pages you have the wp_footer string.


<?php

add_action(‘wp_footer’, ‘add_googleanalytics’);

function add_googleanalytics() ?>

// Paste your Google Analytics code here

<?php ?>



Add Google Analytics

Add a Favicon to your Blog

Every blog deserves to have its own identity. You can add this identity by adding the favicon code in your header.php file, or you can make it easier for yourself by simply adding the following code in your functions.php file.


// add a favicon to your

function blog_favicon()

echo ‘<link rel=”Shortcut Icon” type=”image/x-icon” href=”‘.get_bloginfo(‘wpurl’).’http://cdn3.wpbeginner.com/favicon.ico” />’;


add_action(‘wp_head’, ‘blog_favicon’);



Add a Favicon to your Blog

Add a Favicon to your Blog

Every blog deserves to have its own identity. You can add this identity by adding the favicon code in your header.php file, or you can make it easier for yourself by simply adding the following code in your functions.php file.


// add a favicon to your

function blog_favicon()

echo ‘<link rel=”Shortcut Icon” type=”image/x-icon” href=”‘.get_bloginfo(‘wpurl’).’http://cdn3.wpbeginner.com/favicon.ico” />’;


add_action(‘wp_head’, ‘blog_favicon’);



Add a Favicon to your Blog

Remove WordPress Version Number

You should always encourage your clients to upgrade to the latest version, so you don’t have this problem. But if you are working with a client that does not want to upgrade, then it is essential that you remove your WordPress version number from your WordPress header, RSS feeds, and all other locations. To do this, add the following code:


function wpbeginner_remove_version()

return ”;


add_filter(‘the_generator’, ‘wpbeginner_remove_version’);



Remove WordPress Version Number

Add a Custom Dashboard Logo

When creating themes for a client, you can use this as one of the perks to the theme. All you have to do is paste the following code below:


//hook the administrative header output

add_action(‘admin_head’, ‘my_custom_logo’);


function my_custom_logo()

echo ‘

<style type=”text/css”>

#header-logo background-image: url(‘.get_bloginfo(‘template_directory’).’/images/custom-logo.gif) !important;

</style>

‘;



Add a Custom Dashboard Logo

Change the Footer in WordPress Admin Panel

You can change the footer of your Free or Custom WordPress themes by adding the necessary links. Simply paste the following code:


function remove_footer_admin () WordPress Tutorials: <a href=”http://www.wpbeginner.com” target=”_blank”>WPBeginner</a></p>’;


add_filter(‘admin_footer_text’, ‘remove_footer_admin’);



Change the Footer in WordPress Admin Panel

Dynamic Copyright Date in WordPress Footer

Often you will come across sites with outdated copyright dates. Some sites show the current year as their copyright date. Both of these are annoying, and it shows that the site designer was lazy. In order to give your users a little background info about your site, you should display the copyright date as such: © 2006 – 2010. We can do this by simply pasting the following code:


function comicpress_copyright()

global $wpdb;

$copyright_dates = $wpdb->get_results(”

SELECT

YEAR(min(post_date_gmt)) AS firstdate,

YEAR(max(post_date_gmt)) AS lastdate

FROM

$wpdb->posts

WHERE

post_status = ‘publish’

“);

$output = ”;

if($copyright_dates)

$copyright = “&copy; ” . $copyright_dates[0]->firstdate;

if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate)

$copyright .= ‘-’ . $copyright_dates[0]->lastdate;


$output = $copyright;


return $output;


Once you add this function, then open your footer.php file and add the following code wherever you like to display the dynamic copyright date:


<?php echo comicpress_copyright(); ?>



Dynamic Copyright Date in WordPress Footer

Enable Post Thumbnails in WordPress

To do this, you must enable the post thumbnails inside your functions.php file. Paste the code below:


add_theme_support( ‘post-thumbnails’ );


Then simply place the following code inside your loop where you want to display the thumbnail:


<?php the_post_thumbnail(); ?>


For More Details : http://www.youtube.com/watch?v=fUfgmRCPI0E#t=147



Enable Post Thumbnails in WordPress

Add Author Profile Fields

If you want to create a more versatile author page, then you would need to add additional fields to the author profile. The code below will show you how to add additional twitter and facebook fields, but you can use it to add any other field that you like.


function my_new_contactmethods( $contactmethods )

// Add Twitter

$contactmethods['twitter'] = ‘Twitter’;

//add Facebook

$contactmethods['facebook'] = ‘Facebook’;


return $contactmethods;


add_filter(‘user_contactmethods’,'my_new_contactmethods’,10,1);


You can then call the fields in your author.php template by adding the following code:


<?php echo $curauth->twitter; ?>



Add Author Profile Fields

Disable Search in WordPress

When using WordPress as a CMS, sometimes the search feature becomes unnecessary. You can remove the search bar from the design, but the functionality still remains. You can add the following function and disable the search function:


function fb_filter_query( $query, $error = true )


if ( is_search() )

$query->is_search = false;

$query->query_vars[s] = false;

$query->query[s] = false;


// to error

if ( $error == true )

$query->is_404 = true;


add_action( ‘parse_query’, ‘fb_filter_query’ );

add_filter( ‘get_search_form’, create_function( ‘$a’, “return null;” ) );



Disable Search in WordPress

Enable Adsense Shortcode

Adsense is one of the most popular ad elements used by bloggers. Theme designers can place the adsense box in one spot which limits the users. If you want to give your client the ability to add the adsense anywhere, then you can create a shortcode for the adsense using this function:


function showads()

return ‘<div id=”adsense”><script type=”text/javascript”><!–

google_ad_client = “pub-XXXXXXXXXXXXXX”;

google_ad_slot = “4668915978″;

google_ad_width = 468;

google_ad_height = 60;

//–>

</script>


<script type=”text/javascript”

src=”http://pagead2.googlesyndication.com/pagead/show_ads.js”>

</script></div>’;


add_shortcode(‘adsense’, ‘showads’);



Enable Adsense Shortcode

Custom Excerpt Length

By default the excerpt length is capped at 55 words. Many theme designers like to have the flexibility that is why WordPress lets you customize the excerpt length with this function:


function new_excerpt_length($length)

return 100;


add_filter(‘excerpt_length’, ‘new_excerpt_length’);



Custom Excerpt Length

Customize Excerpt More [...]

// custom excerpt ellipses for 2.9

function custom_excerpt_more($more)

return ‘…’;


add_filter(‘excerpt_more’, ‘custom_excerpt_more’);


/* custom excerpt ellipses for 2.8-

function custom_excerpt_more($excerpt)

return str_replace(‘[...]‘, ‘…’, $excerpt);


add_filter(‘wp_trim_excerpt’, ‘custom_excerpt_more’);

*/



Customize Excerpt More [...]

Display Twitter Followers Count and More

There are widgets that display Twitter followers count, but those are limited and ugly. You can use this function to customize the way your twitter followers count look on your blog. Simply paste the code below:


function rarst_twitter_user( $username, $field, $display = false )

$interval = 3600;

$cache = get_option(‘rarst_twitter_user’);

$url = ‘http://api.twitter.com/1/users/show.json?screen_name=’.urlencode($username);


if ( false == $cache )

$cache = array();


// if first time request add placeholder and force update

if ( !isset( $cache[$username][$field] ) )

$cache[$username][$field] = NULL;

$cache[$username]['lastcheck'] = 0;


// if outdated

if( $cache[$username]['lastcheck'] < (time()-$interval) )


// holds decoded JSON data in memory

static $memorycache;


if ( isset($memorycache[$username]) )

$data = $memorycache[$username];


else

$result = wp_remote_retrieve_body(wp_remote_request($url));

$data = json_decode( $result );

if ( is_object($data) )

$memorycache[$username] = $data;


if ( is_object($data) )

// update all fields, known to be requested

foreach ($cache[$username] as $key => $value)

if( isset($data->$key) )

$cache[$username][$key] = $data->$key;


$cache[$username]['lastcheck'] = time();


else

$cache[$username]['lastcheck'] = time()+60;


update_option( ‘rarst_twitter_user’, $cache );


if ( false != $display )

echo $cache[$username][$field];

return $cache[$username][$field];


Then place the following code where you want to display the count in your theme file:


echo rarst_twitter_user(‘wpbeginner’, ‘name’).’ has ‘.

rarst_twitter_user(‘wpbeginner’, ‘followers_count’).’ followers after ‘.

rarst_twitter_user(‘wpbeginner’, ‘statuses_count’).’ updates.’;



Display Twitter Followers Count and More

Adding an Author Image and Bio Box in WordPress, and Linking to a Google+ Profile

Sorry, no attachments exist.

Adding an Author Image and Bio Box in WordPress, and Linking to a Google+ Profile



Adding an Author Image and Bio Box in WordPress, and Linking to a Google+ Profile

All In One WP Security & Firewall

Sorry, no attachments exist.


A comprehensive, user-friendly, all in one WordPress security and firewall plugin for your site.


A COMPREHENSIVE, EASY TO USE AND WELL SUPPORTED WORDPRESS SECURITY PLUGIN


WordPress itself is a very secure platform. However, it helps to add some extra security and firewall to your site by using a security plugin that enforces a lot of good security practices.



All In One WP Security & Firewall

Sunday, November 24, 2013

PHP Time ago like facebook function

<?php

function ago($timestamp)

$difference = time() – strtotime($timestamp);

$periods = array(‘second’, ‘minute’, ‘hour’, ‘day’, ‘week’, ‘month’, ‘years’, ‘decade’);

$lengths = array(’60′, ’60′, ’24′, ’7′, ’4.35′, ’12′, ’10′);

for($j = 0; $difference >= $lengths[$j]; $j++) $difference /= $lengths[$j];

$difference = round($difference);

if($difference != 1) $periods[$j] .= “s”;

return “$difference $periods[$j] ago”;

echo ago(’2013-11-28 09:50:28′);

?>


PHP Time ago like facebook function

NextScripts: Social Networks Auto-Poster

Sorry, no attachments exist.
This plugin automatically publishes posts from your blog to your Social Network accounts such as Facebook, Twitter, Google+(Google Plus), Blogger, Tumblr, …

Automatically re-publishes blogposts to Facebook, Twitter, Google+, Pinterest, LinkedIn, Blogger, Tumblr, Delicious, Plurk, etc profiles and/or pages


NextScripts: Social Networks Auto-Poster

Magento product review on sidebar extension

Sorry, no attachments exist.

Magento product review on sidebar extension


Magento product review on sidebar extension

Wordpress Extension Add Link to Facebook

Sorry, no attachments exist.

Wordpress Extension Add Link to Facebook


Wordpress Extension Add Link to Facebook

Thursday, November 21, 2013

Saturday, November 16, 2013

Wordpress Extension Admin Drop Down Menu

Sorry, no attachments exist.

All admin links available in a neat horizontal drop down menu. Saves lots of screen real estate!

Wordpress Extension Admin Drop Down Menu


Wordpress Extension Admin Drop Down Menu

Wednesday, November 6, 2013

Custom Social networking sharing link

https://www.linkedin.com/cws/share?url=SITE_URL
http://twitter.com/home?status=SITE_URL
https://plus.google.com/share?url=SITE_URL
http://www.facebook.com/share.php?u=SITE_URL

Thursday, October 10, 2013

HTML and Javascript to share page on social networing site

<a href="#" onclick="window.open('https://plus.google.com/share?url='+encodeURIComponent(location.href), 'facebook-share-dialog', 'width=626,height=436'); return false;" class="icon">Google Icon</a>
            <a href="#" onclick="window.open('http://twitter.com/home?status='+encodeURIComponent(location.href), 'facebook-share-dialog', 'width=626,height=436'); return false;" class="icon">Twitter Icon</a>
            <a href="#" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(location.href), 'facebook-share-dialog', 'width=626,height=436'); return false;" class="icon">Facebook Icon</a>

Script for to remove the cache

make one cache-clear.php file into your root folder and paste following code:
  require_once (“app/Mage.php”); 
 umask(0); 
 Mage::run(); 
 Mage::app()->getCache()->clean(); 
 exit(“done”); 
 ?> 
can call that file with :http://yourdomainname/cache-clear.php

How To Setup Multiple Magento Stores and Web-site

There are numerous ways to setup multiple Magento stores that all share the same codebase and backend, but what method you use depends on your needs.
This article is written with cPanel in mind, though the methodologies listed below apply no matter what control panel you’re using. You will need Magento 1.4.x or greater installed too.
Jump To Section
(A)        Multi-Web-Site, Multi-Domain Setup :-
Follow Multi Web-Site and Multi Store Instructions.
1: Categories
First, will need to create our Categories.  Since all three websites will be sharing the same catalog, we will be using the default root Category in Catalog -> Categories -> Manage Categories and will be creating our categories under that root category (i.e. Clothing, Electronics, etc.).
These categories (Clothing, Electronics) should be set as both “Is Active” from the General Information tab and “Is Anchor” from the Display Settings tab for them to appear on the frontend of your Magento shop.  (***NOTE: If the websites will not be sharing the same catalog, a Root Category must be created for each website.  Thus, if there are 3 websites, there will be 3 Root Categories with subcategories under them.)
2: Store Configuration in the Magento Admin
1. Now that we have created our Categories, it’s time to create our websites by going to System -> Manage Stores and clicking the “Create Website” button.
    Name – domain name of our new website
    Code – a parameter that will be used in configuring the Apache web server to point to that particular domain name
2. Once the website has been created, we’ll create the store corresponding to this website by clicking on the “Create Store” button in System -> Manage Stores.
    Website – website to which this store will be associated
    Name – the same as the website name
    Root Category – the root category that will be used for this store. (Refer to Step 1 for Details)
3. Then, we create the store view which is the interface that the customer will be able to access on the frontend.  Click the “Create Store View” button in System -> Manage Stores.
    Store – store to which this view will be associated
    Name – name of this store view (i.e. English Version, German Version, etc.)
    Code – code for this store view
    Status – if enabled, this store view will be accessible from our frontend, otherwise, it will not be accessible
4. After the Store has been created, we need to configure the Unsecure Base URL and Secure Base URL under System -> Configuration -> General -> Web.  Before we set their respective base URLs, we first need to ensure that the configuration scope is set to the domain1.com website to define which site we are working on.
Then, we modify the base URLs for both Unsecure:
and Secure:
with the corresponding domain name by unchecking the ”Use default [STORE VIEW]” checkbox and then save the configuration.
5. Now we just repeat Steps 2-4 for the other two websites, domain2.com and domain3.com by replacing the fields with their respective information.
3: Store Configuration in the Server
(B)  Two Way of Store Configuration :- Choose as Like You .
First Way :-
1: Store Configuration in the Server Side.
1. Now we re-configure the Apache configuration file, httpd.conf, for all domains to set the DocumentRoot to our Magento directory.  In this case, the directory is /var/www/http

    ServerAdmin webmaster@domain1.com
    DocumentRoot /var/www/http
    ServerName domain0.com

    ServerAdmin webmaster@domain2.com
    DocumentRoot /var/www/http
    ServerName domain1.com

    ServerAdmin webmaster@domain3.com
    DocumentRoot /var/www/http
    ServerName domai2.com
2. Edit the .htaccess file at /var/www/http/.htaccess and add the following lines below:
SetEnvIf Host www\.domain1\.com MAGE_RUN_CODE=domain1_com
SetEnvIf Host www\.domain1\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^domain1\.com MAGE_RUN_CODE=domain1_com
SetEnvIf Host ^domain1\.com MAGE_RUN_TYPE=website
SetEnvIf Host www\.domain2\.com MAGE_RUN_CODE=domain2_com
SetEnvIf Host www\.domain2\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^domain2\.com MAGE_RUN_CODE=domain2_com
SetEnvIf Host ^domain2\.com MAGE_RUN_TYPE=website
SetEnvIf Host www\.domain3\.com MAGE_RUN_CODE=domain3_com
SetEnvIf Host www\.domain3\.com MAGE_RUN_TYPE=website
SetEnvIf Host ^domain3\.com MAGE_RUN_CODE=domain3_com
SetEnvIf Host ^domain3\.com MAGE_RUN_TYPE=website
3. Restart Apache Server
If you are on a Red Hat based distribution, you’ll be able to type service apache restart.  For other distributions, you’ll want to type apachectl restart.  (***NOTE: The second option here is different than “apachectl graceful” which will run a graceful restart and reload configuration files, without terminating current connections.  We don’t have any visitors to our site yet, so it’s okay to do a “apachectl restart”.)
4: We’re Ready to Go!
After we’ve complete all of these steps we should now see all 3 domains in our backend:
All that’s left now is to add products to the catalog and give each site a custom theme if we wish to do so.  Many people are taking advantage of Magento’s powerful multi-store functionality, whether it’s to set up stores with multiple languages, different catalogs and even the same catalogs (as in our example) with different front ends as a marketing vehicle.  No matter which you decide to use Magento’s powerful features for, we hope this post will provide a good starting point to help you get there!
Second Way :-
1: Web-Site &Store Configuration in the Index.php .
Complete Create  Root category And Website, store, store view then process  again. Open index.php in magento  Root Folder some changes Doc file according.
First,  Find this line code and replace.
Find  = $mageFilename = MAGENTO_ROOT . ‘/app/Mage.php’;
Replace = $mageFilename = MAGENTO_ROOT . ‘../app/Mage.php’;
Second ,  Find this line code and replace.
Find  =  Mage::run($mageRunCode, $mageRunType);
Replace  =
$i=$_SERVER['REQUEST_URI'];
switch ($i):
    case ‘www.domain1.com’:
         Mage::run(“domain1″,”website”);
        break;
    case ‘www.domain2.com’:
         Mage::run(“domain2″,”website”);
        break;
    case ‘www.domain3.com’:
         Mage::run(“domain3″,”website”);
        break;
    default:
       Mage::run(“default”,”website”);
endswitch;
After Completed two major change save index.php file in root folder. Delete all cache and Re-indexing admin panel. After restart apache server. Then check our Multi-domain website is ready for running.
Magento’s provide  powerful multi-store functionality . I hope this instruction  will provide a good starting point to help you get there!
End .

Saturday, October 5, 2013

Magento add custom textbox,select box to existing system -> configuration tab.

if we want to add custom fields like textbox,select box to existing system -> configuration tab -> catalog.

<?xml version="1.0"?>
<config>
   <sections>
        <catalog>
            <groups>
                <frontend>
                    <fields>
                        <mayankpatel translate="label">
                            <label>Custom Textbox Value</label>
                            <frontend_type>text</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>1</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </mayankpatel>
                      </fields>
                </frontend>
            </groups>
        </catalog>
    </sections>
</config>

Tuesday, October 1, 2013

Magento replace quantity text box to select box

In the addtocart.phtml file find the following code(around line 33)
<input name="qty" type="text" class="input-text qty" id="qty" maxlength="12" value="<?php echo $this->getMinimalQty($_product) ?>" />



Replace with this code:

This code shows the “Available Qty for Product”.
<select class="input-text qty" name="qty" id="qty">
  <?php $i = 1 ?>
  <?php do { ?>
    <option value="<?php echo $i?>">
      <?php echo $i?>
      <?php $i++ ?>
    </option>
    <?php } while ($i <= (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()) ?></select>


This code shows the “Maximum Qty Allowed in Shopping Cart”.

<select class="input-text qty" name="qty" id="qty">
  <?php $i = 1 ?>
  <?php do { ?>
    <option value="<?php echo $i?>">
      <?php echo $i?>
      <?php $i++ ?>
    </option>
    <?php } while ($i <= (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getMaxSaleQty()) ?></select>

Magento – Delete all cancelled magento orders

$collection = Mage::getResourceModel('sales/order_collection')
            ->addAttributeToSelect('*')
            ->setPageSize(1000)
            ->addFieldToFilter('status', 'canceled')
     ->load();

foreach ($collection as $col) {
  Mage::log($col->getIncrementId() . ' order deleted ');
    try {
         $col->delete();
    } catch (Exception $e) {
        throw $e;
    }
}

How to Add Custom Class to top links

To Add Custom Class to top links  in Magneto

1) Open XML files for Top links And Add following tag

<reference name=”top.links”>
<action method=”addLink” translate=”label title” module=”customer”><label>Account</label><url helper=”customer/getAccountUrl”/><title>Account</title><prepare/><urlParams/><position>10</position><liParams/>
<aParams>class=”top-link-account”</aParams></action>
</reference>

SELECT,INSERT,UPDATE,AND DELETE DATA (CRUD) IN MAGENTO

I have a database table named “test” with the following fields given below:

SELECT DATA

$model = Mage::getModel('test/test');
$collection = $model->getCollection();
foreach($collection as $item){
    print_r($item->getData());
    print_r($item->getTitle());
}

INSERT DATA

$data = array('title'=>'hello EWA','content'=>'This is for the Testing on the Insert data','status'=>1);
$model = Mage::getModel('mytestimonial/mytestimonial')->setData($data);
try {

       $insertId = $model->save()->getId();
        echo "Data has been saved successfully. Insert ID: ".$insertId;
    } catch (Exception $e){
     echo $e->getMessage();
}

UPDATE DATA

// $sid = $this->getRequest()->getParam('id');
$sid = 5;
$data = array('title'=>'hello EWA','content'=>'This is for the Testing on the Update data','status'=>0);
$model = Mage::getModel('mytestimonial/mytestimonial')->load($sid)->addData($data);
try {
        $model->setId($sid)->save();
        echo "Data has been updated successfully.";
       
    } catch (Exception $e){
        echo $e->getMessage();
}

DELETE DATA

$sid is the database table row id to be deleted.

// $sid = $this->getRequest()->getParam('id');
$sid = 5;
$model = Mage::getModel('mytestimonial/mytestimonial');
try {
        $model->setId($sid)->delete();
        echo "Data deleted successfully.";
       
    } catch (Exception $e){
        echo $e->getMessage();
}

DISPLAY RELATED PRODUCTS ANYWHERE IN MAGENTO

<?php

//Start loading a product resources
$product = Mage::getModel('catalog/product')->load($productId);

//save the product into the registry
Mage::register('product', $product);

//display $product's related products
echo $this->getLayout()->createBlock('catalog/product_list_related')->setTemplate('catalog/product/list/related.phtml')->toHtml();

?>

DISPLAY LIST OF ALL MANUFACTURERS IN MAGENTO

<?php
$product = Mage::getModel('catalog/product');
   
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
                  ->setEntityTypeFilter($product->getResource()->getTypeId())
                  ->addFieldToFilter('attribute_code', 'manufacturer');

$attribute = $attributes->getFirstItem()->setEntity($product->getResource());
$manufacturers = $attribute->getSource()->getAllOptions(false);
     
echo "<pre>";
print_r($manufacturers);
echo "</pre>";

?>

RELATED PRODUCTS ON PRODUCT DESCRIPTION PAGE IN MAGENTO

Step 1. Open catalog.xml file for this navigate to the app/design/frontend/default/your_custom_theme/layout/ or you can find this file app/design/frontend/base/default/layout/ open it in the editor of your choice.

Step 2. In catalog.xml search for the catalog_product_view section
<block type="catalog/product_list_related" name="catalog.product.related" before="-" template="catalog/product/list/related.phtml"/>

Step 3. Search for the catalog_product_view section again and copy and paste the code as like given below:
<reference name="content">
<block type="catalog/product_view" name="product.info" template="catalog/product/view.phtml">
<block type="catalog/product_list_related" name="catalog.product.related" as="related" template="catalog/product/list/related.phtml"/>
</block>
</reference>

Step 4. Now navigate to the app/design/frontend/default/your_custom_theme/template/catalog/product/view.phtml or you can find this file app/design/frontend/base/default/template/catalog/product/view.phtml open the file in the editor of your choice, insert the given below code in the desired position where you want to display the related product block in the product description page.
<?php echo $this->getChildHtml('related'); ?>

Step 5. For editing the look of the related products Navigate to the app/design/frontend/default/your_custom_theme/template/catalog/product/list/related.phtml or you can find this file app/design/frontend/base/default/template/catalog/product/list/related.phtml, from here you can change the look and feel of the related products.

Step 6. Now refresh the cache from the Magento admin and delete the browser cache and refresh the page.

Magento add attribute to filter conditions for products collection

General Product Collection:
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addAttributeToFilter('status',1); //only enabled product
$collection->addAttributeToFilter('visibility',array("neq"=>1)); //except not visible individually
$collection->addAttributeToSelect(array('name','url','small_image')); //add product attribute to be fetched
//$collection->getSelect()->order('rand()');   //uncomment for getting the products in random order
$collection->addStoreFilter();
if(!empty($collection))
{
foreach ($collection as $_product):
echo $_product->getName();   //get product name
endforeach;
}else
{
echo 'There is no products';
}


Get All Products of a category or Product collection filter by the category

$collection = Mage::getResourceModel('catalog/product_collection')
->setStoreId($this->getStoreId())
->addCategoryFilter($category);


$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image'))->addAttributeToFilter('name', array('like' => 'Nok%'))->load();

a) Equals: eq

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'status'))->addAttributeToFilter('status', array('eq' => 1))->load();

b) Not Equals – neq

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image','sku'))->addAttributeToFilter('sku', array('neq' => 'test-product'))->load();

c) In – in

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku')) ->addAttributeToFilter('id', array('in' => array(20,24,100)))->load();

d) Not In – nin

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))->addAttributeToFilter('id', array('nin' => array(20,24,100)))->load();

e) Like – like

$products = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku')) ->addAttributeToFilter('name', array('like' => 'Nok%'))->load();

f) Not Like – nlike

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku')) ->addAttributeToFilter('name', array('nlike' => 'Nok%'))->load();

g) NULL – null

$products = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))   ->addAttributeToFilter('description', 'null') ->load();

h)  Not NULL – notnull

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))->addAttributeToFilter('description', 'notnull')->load();

i) Greater Than – gt

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))->addAttributeToFilter('id', array('gt' => 10))->load();

j) Less Than – lt

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))->addAttributeToFilter('id', array('lt' => 10))->load();

k) Greater Than or Equals To- gteq

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))->addAttributeToFilter('id', array('gteq' => 20))->load();

l) Less Than or Equals To – lteq

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku')) ->addAttributeToFilter('id', array('lteq' => 20))->load();

Display All Active Categories

$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*')
->addIsActiveFilter();

Display Active Categories Of Any Particular Level in Magento

$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*')
->addIsActiveFilter()
->addLevelFilter(1)
->addOrderField('name');

Display Top level categories only in Magento

<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php if (count($_categories) > 0): ?>
<ul>
<?php foreach($_categories as $_category): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
<?php echo $_category->getName() ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

Magento display root categories and subcategories

<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry('current_category') ?>
<?php if (count($_categories) > 0): ?>
    <ul>
    <?php foreach($_categories as $_category): ?>
    <li>
    <a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
    <?php echo $_category->getName() ?> <!--//Top Level Category Listing-->
    </a>
    <?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
    <?php $_subcategories = $_category->getChildrenCategories() ?>
    <?php if (count($_subcategories) > 0): ?>
    <ul>
    <?php foreach($_subcategories as $_subcategory): ?>
    <li>
    &nbsp;&nbsp;&nbsp;<a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>"> <!--//Sub Category Listing-->
    <?php echo $_subcategory->getName() ?>
    </a>
    </li>
    <?php endforeach; ?>
    </ul>
    <?php endif; ?>
    </li>
    <?php endforeach; ?>
    </ul>
<?php endif; ?>

Friday, September 27, 2013

Magento print select query for products

To print select query : app\code\core\mage\catalog\model\resources\collection\abstract.php

Monday, September 23, 2013

Magento - Sort by Date Added

copying app/code/core/Mage/Catalog/Block/Product/List.php into app/code/local and adding some sorting code at the end of its _getProductCollection() method:


 / sort by created_at date or entity_id
if(!isset($_GET['order'])) {
    $this->_productCollection->getSelect()->reset( Zend_Db_Select::ORDER );
    $this->_productCollection->getSelect()->order('e.entity_id desc');
}
return $this->_productCollection;

Friday, September 13, 2013

To show the Name of Brands in magento

<div class="brand">
<?php
$product = Mage::getModel('catalog/product');
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')->setEntityTypeFilter($product->getResource()->getTypeId())->addFieldToFilter('attribute_code', 'manufacturer');
$attribute = $attributes->getFirstItem()->setEntity($product->getResource());
$manufacturers = $attribute->getSource()->getAllOptions(false);
?>
<ul id="manufacturer_list"><?php foreach ($manufacturers as $manufacturer): ?>
<li><a href="catalogsearch/advanced/result/?manufacturer[]=<?php echo $manufacturer['value'] ?>"><?php echo $manufacturer['label'] ?></a>
</li>
<?php endforeach; ?>   </ul>
</div>

Product Sold quantity display in your view page in magento.

<?php
$sku = nl2br($_product->getSku());
$_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addOrderedQty()
    ->addAttributeToFilter('sku', $sku)
    ->setOrder('ordered_qty', 'desc')
    ->getFirstItem();
$product = $_productCollection;

echo 'Already sold '.(int)$product->ordered_qty;
?>

Showing the Best Seller Product by code..

Step 1: Create a file app/code/local/Mage/Catalog/Block/Product/Bestseller.php and the following lines of code in it

class Mage_Catalog_Block_Product_Bestseller extends Mage_Catalog_Block_Product_Abstract{
public function __construct(){
parent::__construct();
$storeId = Mage::app()->getStore()->getId();
$products = Mage::getResourceModel('reports/product_collection')
->addOrderedQty()
->addAttributeToSelect('*')
->addAttributeToSelect(array('name', 'price', 'small_image'))
->setStoreId($storeId)
->addStoreFilter($storeId)
->setOrder('ordered_qty', 'desc'); // most best sellers on top
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products );

$products->setPageSize(3)->setCurPage(1);
$this->setProductCollection($products);
}
}



Step 2: Create a file app/design/frontend/default/YourTheme/template/catalog/product/bestseller.phtml file and add the following lines of code in it

<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<div class="page-title">
<h2><?php echo $this->__('Best Seller Products') ?></h2>
</div>
<?php $_collectionSize = count($_products->getItems()) ?>
<table class="products-grid" id="products-grid-table">
<?php $i=1; foreach ($_products->getItems() as $_product): ?>
<?php if ($i%1!==0): ?>
<tr>
<?php endif ?>
<td id="td_<?php echo $i;?>" <?php if($i%3==0 or $i==$_collectionSize){echo 'class="last"';} ?> >
<?php contentBlock('top') ?>
<div id="cont_<?php echo $i;?>">
<h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
<a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(122, 109); ?>" width="122" height="109" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
</a>
<div class="a-center">
<?php if($_product->getRatingSummary()): ?>
<?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
<?php endif; ?>
<?php echo $this->getPriceHtml($_product, true) ?>
<?php if($_product->isSaleable()): ?>
<button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
<div class="clear"></div>
<?php else: ?>
<p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span></p>
<div class="clear"></div>
<?php endif; ?>
<ul class="add-to-links">
<?php if ($this->helper('wishlist')->isAllow()) : ?>
<li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>"><?php echo $this->__('Add to Wishlist') ?></a></li>
<?php endif; ?>
<?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
<li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Add to Compare') ?></a></li>
<?php endif; ?>
</ul>
<?php if($_product->getevent_date()) {echo $_product->getevent_date();} ?>
</div>
</div>
</td>
<?php if ($i%3==0 or $i==$_collectionSize): ?>
</tr>
<?php endif ?>
<?php $i++; endforeach; $kol = $_collectionSize; ?>
</table>
<?php endif; ?>


Step 3: This above files will create a list of best selling products which can be shown anywhere on your Magento store. All you have to do is place the following line of code block in your template to show the best selling products.

{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml"}}

Update products price and special price with sku-simple script in magento

 I am searching with this topic but all I find the paid extension for bulk product updation of price. so I made a simple script to update the product with special price and price through their respective sku.

<?php
/**
 * @author      MagePsycho <info@magepsycho.com>
 * @website     http://www.magepsycho.com
 * @category    Export / Import
 */
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
Mage::register('isSecureArea', 1);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

set_time_limit(0);
ini_set('memory_limit','1024M');

/***************** UTILITY FUNCTIONS ********************/
function _getConnection($type = 'core_read'){
    return Mage::getSingleton('core/resource')->getConnection($type);
}

function _getTableName($tableName){
    return Mage::getSingleton('core/resource')->getTableName($tableName);
}

function _getAttributeId($attribute_code = 'price'){
    $connection = _getConnection('core_read');
    $sql = "SELECT attribute_id
                FROM " . _getTableName('eav_attribute') . "
            WHERE
                entity_type_id = ?
                AND attribute_code = ?";
    $entity_type_id = _getEntityTypeId();
    return $connection->fetchOne($sql, array($entity_type_id, $attribute_code));
}
function _getAttributeId1($attribute_code = 'special_price'){
    $connection = _getConnection('core_read');
    $sql = "SELECT attribute_id
                FROM " . _getTableName('eav_attribute') . "
            WHERE
                entity_type_id = ?
                AND attribute_code = ?";
    $entity_type_id1 = _getEntityTypeId();
    return $connection->fetchOne($sql, array($entity_type_id1, $attribute_code));
}

function _getEntityTypeId($entity_type_code = 'catalog_product'){
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_type_id FROM " . _getTableName('eav_entity_type') . " WHERE entity_type_code = ?";
    return $connection->fetchOne($sql, array($entity_type_code));
}

function _getIdFromSku($sku){
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_id FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    return $connection->fetchOne($sql, array($sku));

}


function _checkIfSkuExists($sku){
    $connection = _getConnection('core_read');
    $sql        = "SELECT COUNT(*) AS count_no FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    $count      = $connection->fetchOne($sql, array($sku));
    if($count > 0){
        return true;
    }else{
        return false;
    }
}

function _updatePrices($data){
    $connection     = _getConnection('core_write');
    $sku            = $data[0];
    $newPrice       = $data[1];
 $specialPrice   = $data[2];
    $productId      = _getIdFromSku($sku);
    $attributeId    = _getAttributeId();
 $attributeId1    = _getAttributeId1();

    $sql = "UPDATE " . _getTableName('catalog_product_entity_decimal') . " cped
                SET  cped.value = ?
            WHERE  cped.attribute_id = ?
            AND cped.entity_id = ?";
$sql1 = "UPDATE " . _getTableName('catalog_product_index_price') . " cpip
                SET  cpip.final_price = ?
            WHERE cpip.entity_id = ?";


    $connection->query($sql, array($newPrice, $attributeId, $productId));
 $connection->query($sql, array($specialPrice, $attributeId1, $productId));
 $connection->query($sql1, array($specialPrice, $productId));

}

/***************** UTILITY FUNCTIONS ********************/

$csv                = new Varien_File_Csv();
$data               = $csv->getData('var/import/prices.csv'); //path to csv
array_shift($data);

$message = '';
$count   = 2;
foreach($data as $_data){
    if(_checkIfSkuExists($_data[0])){
        try{
            _updatePrices($_data);
            $message .= $count . '> Success:: While Updating Price (' . $_data[1] . ') of Sku (' . $_data[0] . '). <br />';
_updatePrices($_data);
            $message .= $count . '> Success:: While Updating Price (' . $_data[2] . ') of Sku (' . $_data[0] . '). <br />';

        }catch(Exception $e){
            $message .=  $count .'> Error:: While Upating  Price (' . $_data[1] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
$message .=  $count .'> Error:: While Upating  Price (' . $_data[2] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
        }
    }else{
        $message .=  $count .'> Error:: Product with Sku (' . $_data[0] . ') does\'t exist.<br />';
    }
    $count++;
}
echo $message;
?>



save this script to your root file and run it...
and for csv your field should be:

sku    price   special_price



The csv save in var/import/prices.csv
Note:- prices.csv is the name of csv file.

Reindexing of Product Flat Data in magento:

You have to truncate all the 'catalog_product_flat_i' table:
where 'i' can be 1,2,3,4,....

In my case there are 3 table so i fire this query to my phpmyadmin:
TRUNCATE `catalog_product_flat_1`;
TRUNCATE `catalog_product_flat_2`;
TRUNCATE `catalog_product_flat_3`;

How to increase page speed in magento:('without merge css and javascript files')

In you htaccess file do chages as:

Uncomment the line
 php_flag zlib.output_compression on
means remove '#' from starting of php_flag zlib.output_compression on.

write these line in your htaccess file

<IfModule mod_expires.c>

# Enable expirations

ExpiresActive On

# Default directive

ExpiresDefault "access plus 1 year"

# My favicon

ExpiresByType image/x-icon "access plus 1 year"

# Images

ExpiresByType image/gif "access plus 1 year"

ExpiresByType image/png "access plus 1 year"

ExpiresByType image/jpg "access plus 1 year"

ExpiresByType image/jpeg "access plus 1 year"

# CSS

ExpiresByType text/css "access 1 year"

# Javascript

ExpiresByType application/javascript "access plus 1 year"

</IfModule>


Uncomment the lines:

SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
Header append Vary User-Agent env=!dont-vary


means remove '#' from starting of these lines.

How to overwrite magento controller in local directory

For Example you have to overwrite Mage/Contacts/controller/IndexController.php
Step 1: First you have to make a xml in app/etc/modules/ with name CompanyName_NameSpace.xml true local 0.1.0

Step2: You have to create the folders if not exist in local/CompanyName/NameSpace/etc/ local/CompanyName/NameSpace/controllers/ In etc folder you have to create a config.xml file Shweta_Newscontacts In controllers folder copy the Mage/Contacts/controller/IndexController.php file and include the lines: include_once('Mage/Contacts/controllers/IndexController.php'); and change the class name as: class CompanyName_NameSpace_IndexController extends Mage_Core_Controller_Front_Action Now apply changes in the file you wanted. Now also, Magento take local pool file instead of core pool.

customize of label "choose an option" of configurable product in magento

Step 1: Change in catalog/product/view/type/options/configurable.phml getProduct(); $_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes()); ?> isSaleable() && count($_attributes)):?>
getAttributeId(); $_attributeInfo = Mage::getModel('eav/entity_attribute')->load($_attributeId); $_attributeLabel = str_replace(' ','-',strtolower($_attributeInfo->getFrontendLabel())); ?>
decoratedIsLast){?> class="last">
Step 2: js/varien/configurable.js replace line 171 = element.options[0] = new Option(element.config.label, '');

 Step 3: app/design/frontend/default/grayscale/template/catalog/product/view/type/options/configurable.php change this line: 'label' => 'choose a '.$attribute->getLabel(),

Monday, August 26, 2013

magento remove Product Type virtual product,bundle product and downloadable product.

app/code/core/mage/catalog/model/product/type.php

static public function getOptionArray()
    {
        $options = array();
        foreach(self::getTypes() as $typeId=>$type)
        {
            if($type['label'] != "Virtual Product" && $type["label"] != "Grouped Product" && $type["label"] != "Downloadable Product" && $type["label"] != "Bundle Product")
            {
                $options[$typeId] = Mage::helper('catalog')->__($type['label']);
            }
        }

        return $options;
    }

Wednesday, August 7, 2013

Magento display all categories from product id (product listing page and search product listing page).

$product_model = Mage::getModel('catalog/product');
$product_model->reset();
$_product = $product_model->load($_product->getId());
$all_cats = $product_model->getCategoryIds($_product);
foreach($all_cats as $key => $_categoryId)
{
$category = Mage::getModel('catalog/category')->load($_categoryId);
echo "<br />".$category->getName();
}

Monday, August 5, 2013

PHP Script to calculate time from specific date(Like Facebook)

function time_passed($timestamp)

    $timestamp      = (int) $timestamp;
    $current_time   = time();
    $diff           = $current_time - $timestamp;
  
    $intervals      = array ('year' => 31556926, 'month' => 2629744, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute'=> 60);
  
    if ($diff == 0)
    {
        return 'just now';
    }  

    if ($diff < 60)
    {
        return $diff == 1 ? $diff . ' second ago' : $diff . ' seconds ago';
    }      

    if ($diff >= 60 && $diff < $intervals['hour'])
    {
        $diff = floor($diff/$intervals['minute']);
        return $diff == 1 ? $diff . ' minute ago' : $diff . ' minutes ago';
    }      

    if ($diff >= $intervals['hour'] && $diff < $intervals['day'])
    {
        $diff = floor($diff/$intervals['hour']);
        return $diff == 1 ? $diff . ' hour ago' : $diff . ' hours ago';
    }  

    if ($diff >= $intervals['day'] && $diff < $intervals['week'])
    {
        $diff = floor($diff/$intervals['day']);
        return $diff == 1 ? $diff . ' day ago' : $diff . ' days ago';
    }  

    if ($diff >= $intervals['week'] && $diff < $intervals['month'])
    {
        $diff = floor($diff/$intervals['week']);
        return $diff == 1 ? $diff . ' week ago' : $diff . ' weeks ago';
    }  

    if ($diff >= $intervals['month'] && $diff < $intervals['year'])
    {
        $diff = floor($diff/$intervals['month']);
        return $diff == 1 ? $diff . ' month ago' : $diff . ' months ago';
    }  

    if ($diff >= $intervals['year'])
    {
        $diff = floor($diff/$intervals['year']);
        return $diff == 1 ? $diff . ' year ago' : $diff . ' years ago';
    }
}
echo time_passed(strtotime('2012-08-05')) . '<br />';

Thursday, June 6, 2013

server-side GZIP Script in php (define in .htaccess file)

#Gzip
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript text/javascript
</ifmodule>
#End Gzip

Tuesday, June 4, 2013

Export Db as zip

Export Zip files

JQuery date picker

Date Picker

PHP Email Validation

<?php
$email_a = 'joe@example.coddddm';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_b) email address is considered valid.";
}
?>

PHP Script to for global timezone dropdown

Timezone Dropdown

PHP Script to export database.

Export Database

Friday, May 31, 2013

Jquery form submit and image upload through ajax

<a href="http://docs.google.com/file/d/0B4nDLq9K61UvaFhmQk15TEhwVkU/edit?usp=drive_web" target="_blank" class="fileitem-linked" rel="noreferrer">jquery-image-upload.zip</a>

CSS Hack for Google Chrome,Safari,ie7,ie8

@media screen and (-webkit-min-device-pixel-ratio:0)
{
.classname{ background:#ccc; } /*It will works on Google chrome and safari */
}

IE7

.classname{*background:#ccc; } /*It will works on IE7 */
.classname{background:#ccc \9; } /*It will works on IE8 */

Use Mini-Login in Header or anywhere you want!

add in app/design/frontend/default/default/layout/page.xml :
 <block type="customer/form_login" name="mini_login" template="customer/form/mini.login.phtml" />

Then, you just have to call the module : <?php echo $this->getChildHtml('mini_login'?>

Display total weight of cart in the magento

$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();

$weight = 0;
foreach($items as $item) {
    $weight += ($item->getWeight() * $item->getQty()) ;
}

echo $weight;

How to Set Registration Block on Home Page ?

{{block type="Mage_Customer_Block_Form_Register" template="customer/form/register.phtml"}}

Monday, April 29, 2013

PHP Script to sent email with attachments.

sentemail-attachment.zip

PHP Script to create cache

1). Create Folder Name "cache";
2).
ob_start();
$strUrl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

if(file_exists("cache/".basename($strUrl)))
{
require_once("cache/".basename($strUrl));
}
else
{
echo "This is home page content......................";
}
$fp = fopen("cache/".basename($strUrl),"w");
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();

FFMPEG Library for windows php script

FFMPEG Library for windows

How to Print a part of webpage using Javascript


<div dir="ltr" style="text-align: left;" trbidi="on">
<script type="text/javascript">
function printDiv()
{
   var divToPrint=document.getEelementById('areaToPrint');
  newWin= window.open("");
  newWin.document.write(divToPrint.outerHTML);
  newWin.print();
  newWin.close();
}
</script>

<div id="areaToPrint">
The text you want to print or the content you want to print
</div>
</div>

How to add a Bookmark to the Browser using Javascript


<div dir="ltr" style="text-align: left;" trbidi="on">
<script type="text/javascript">
function Add_Bookmark_Favorite(url,title)
{
 if (window.sidebar)
 { // Mozilla Firefox Bookmark
  //Make sure "Load this bookmark in the sidebar is deselected
  window.sidebar.addPanel(title, url,"");
  return false;
 }
 else if( window.external )
 { // IE Favorites
  window.external.AddFavorite( url, title);
  return false;
 }
 else if(window.opera && window.print)
 { // Opera Bookmark
  return !addToFav(url,title)
 }
}
</script>
<a href="" onclick="Add_Bookmark_Favorite('http://www.google.com/','Google')">Bookmark this link</a>

</div>

Check whether site is down or good using php


function VisitSite($url)
{
    //$agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL,$url );
    //curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch,CURLOPT_VERBOSE,false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $page=curl_exec($ch);
    //echo curl_error($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($httpcode >= 200 && $httpcode < 300){
        return true;
    }
    else {
        return false;
    }
}
if(VisitSite('http://www.google.co.in'))
{
       echo "Website looks Good<br />";
}else
{
      echo "Website looks Down<br />";
}

Limit the text area using Javascript

Compress & decrease the page loading time using HTACCESS

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_include mime ^image/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*

Upgrade Phpmyadmin in XAMPP

Just download the latest version of Phpmyadmin from phpmyadmin or download from the link below. http://www.phpmyadmin.net/home_page/downloads.php First take a copy of Phpmyadmin folder in XAMPP or else just rename it in XAMPP then extract the downloaded files into XAMPP folder. And now, take the config.inc.php file from the renamed folder & place it in the new folder, thats it & just check the latest version is running successfully.

Friday, April 19, 2013

Get the post / page ID in functions.php

Usually the global variable $post will give the user all the information of the current post / page. This global variable is not available in functions.php (if the code is not in a function) so you can use the following code snippet to get the ID of the post/page ID based on current URL.

$currenturl = explode('?', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$curpostId = url_to_postid($currenturl [0]);


$curpostId value will be zero if the current page is not a post / page.

Disable Author page in wordpress

Disable Author page in wordpress

SKYPE and WAMP server conflicting

Skype Tools->Options->Advanced->Connection->UNCHECK "use port 80 and 443 as alternative incomming ports".

Manage Cron Job using Putty

Login to SSH via Putty
Type crontab –e
Use “I” for insert
Make the necessary changes
Press Escape
Type :q (to quit without any changes)
Type :wq (to save changes and quit)

Get first Image from Post content in Wordpress

Get first Image from Post content in Wordpress

Payment Gateways and Extensions for Indian Rupee Currency

EBS Payment Gateway India:
WebSite: http://ebs.in/
Downloads:https://support.ebs.in/app/index.php?/default_import/Knowledgebase/List/Index/9

Magento Extension:
https://support.ebs.in/app/index.php?/default_import/Knowledgebase/Article/View/366/0/magento-16-ebs-integration-kit-ver-25

CC Avenue:
WebSite: http://www.ccavenue.com/
Signup Link: https://mars.ccavenue.com/mer_register/mer_register_form_ccav.jsp
Sample Code: Available in merchant account

Magento Extension: http://bluezeal.in/ccavenue4magento/ccavenue-payment-module-for-magento
CC Avenue Integration Scripts:
http://opensourceprogrammer.in/php-script-for-integration-of-ccavenue-payment-gateway
http://world.ccavenue.com/downloads/CCAVenueWorldIntegrationManual.pdf

Face detection using PHP

We need to install Facedetection, OpenCV PHPextensions to use these functions to find the coordinates of the faces. Go through the following resouces for more information.
http://corpocrat.com/2009/08/18/automatic-face-detection-with-php-in-linux/
https://github.com/infusion/PHP-Facedetect/
http://www.xarg.org/project/php-facedetect/


You can detect face without any PHP extension using below Script:
http://devlup.com/programming/php/face-detection-using-php/1140/
http://www.emanueleferonato.com/2010/07/06/php-face-detection-class/


http://www.codediesel.com/algorithms/face-detection-in-images-using-php/


http://svay.com/blog/face-detection-in-pure-php-without-opencv/

Magento: Display Currency Switcher in Header

Magento: Display Currency Switcher in Header

Magento Create Basic Custom Payment Gateway

Magento Create Basic Custom Paument Gateway

Frequently used Putty commands

Database Dump:
mysqldump -u username -h localhost -p dbname > filename.sql

Import Database Dump:
mysql -u username -p -h localhost DATA-BASE-NAME < data.sql

Tar a folder:
tar -cv foldername > foldername.tar

GZip the tar file:
gzip foldername.tar

Extract tar.gz file:
tar -zxvf yourfile.tar.gz

Extract .bz2 file:
bunzip2 yourfile.bz2

Extract tar.bz2file:
tar jxf backup.tar.bz2

Copy files from source to destination: scp local.xml username@hostnameORipaddress:FullFolderTargetPath