Design anchor tag visited link, select link, unvisited link, active link and link open in new tab

If we want to open the link in new tab then we have to use target="_blank" property in anchor tab. Below is the code.

HTML:


CSS for anchor tag:

/* unvisited link */
.anchor-box a:link {
color: green;
}

/* visited link */
.anchor-box  a:visited {
color: #776655;
}

/* mouse over link */
.anchor-box a:hover {
color: red;
}

/* selected link */
.anchor-box a:active {
color: yellow;
}

Output:

If we want to change text-decoration in anchot tag.

Default text-decoration comes text-decoration: underline; if you want to remove unaderline, we have to use text-decoration: none; is our css. Like below

.anchor-box a:link {
color: green;
text-decoration: none;
}

If we want a line in over the link, then we can set as below

.anchor-box a:link {
color: green;
text-decoration: overline;

}

If we want to create link line-through, then we can change like-

.anchor-box a:link {
color: green;
text-decoration: line-through;

}

We can also change anchor tag background color;

.anchor-box a:link {
background-color: red;
color: #ffcc77;
text-decoration: none;
}

we can also change it font family

.anchor-box a:link {
background-color: red;
color: #ffcc77;
text-decoration: none;
font-family: Verdana;
}

DIVI theme- Collapsible Nested Sub Menu Items for Mobile

Question:

How can we do the Collapsible Nested Sub Menu Items on Divi’s Mobile Menu ?

Solution:

Default DIVI mobile menu is shown in the image as below.

If we have to just use the below CSS and script in our site. We can put below CSS and JS script going to WP-admin ->Divi Theme Options -> Integrations -> Add code to the body .

Or In child-theme (if you are using) style and js/script file.

CSS:

#main-header .et_mobile_menu .menu-item-has-children > a { background-color: transparent; position: relative; }
#main-header .et_mobile_menu .menu-item-has-children > a:after { font-family: 'ETmodules'; text-align: center; speak: none; font-weight: normal; font-variant: normal; text-transform: none; -webkit-font-smoothing: antialiased; position: absolute; }
#main-header .et_mobile_menu .menu-item-has-children > a:after { font-size: 16px; content: '\4c'; top: 13px; right: 10px; }
#main-header .et_mobile_menu .menu-item-has-children.visible > a:after { content: '\4d'; }
#main-header .et_mobile_menu ul.sub-menu { display: none !important; visibility: hidden !important;  transition: all 1.5s ease-in-out;}
#main-header .et_mobile_menu .visible > ul.sub-menu { display: block !important; visibility: visible !important; }

Script:

(function($) {
      
    function setup_collapsible_submenus() {
        var $menu = $('#mobile_menu'),
            top_level_link = '#mobile_menu .menu-item-has-children > a';
             
        $menu.find('a').each(function() {
            $(this).off('click');
              
            if ( $(this).is(top_level_link) ) {
                $(this).attr('href', '#');
            }
              
            if ( ! $(this).siblings('.sub-menu').length ) {
                $(this).on('click', function(event) {
                    $(this).parents('.mobile_nav').trigger('click');
                });
            } else {
                $(this).on('click', function(event) {
                    event.preventDefault();
                    $(this).parent().toggleClass('visible');
                });
            }
        });
    }
      
    $(window).load(function() {
        setTimeout(function() {
            setup_collapsible_submenus();
        }, 700);
    });
 
})(jQuery);

Output:

Now, when we will refresh on the front end we should have a mobile menu that looks like the images below.

Our new collapsed mobile menu is as below.

Our new mobile menu expanded one level.

Hope this post will help you :). Feel free to give any suggestion in comment.

PHP/JSON/MYSQL: PHP output JSON Web Service "charset UTF-8" get multi languange data like hindi,franch etc

If we have to add another langauge data like franch,hindi,gujrati etc, we will have to change Collation as "utt8_general_ci".

Below are the detailed code and easy steps.

PHP code:

include_once("conif.php"); // include database config file
//$uid = isset($_GET['uid']) ? mysql_escape_string($_GET['uid']) : "";

$uid = 1;
mysql_query ("set character_set_results='utf8'");// set names mysql query
    if(!empty($uid)){
       $qur =  mysql_query("select name,address from gujrati_data where id ='$uid'");
       $result = array();
   
       while($r = mysql_fetch_array($qur)){
       extract($r);  
          // echo $r['name'];
           //echo $r['address'];
         
           $result[] = array("name" => $name,"email" => $address);
     
    }    
       $json = array("status" => 1, "info" => $result);
    }else{
     
       $json =  array("status" => 0, "msg" => "User ID is Not Define");
    }
    header('Content-Type: application/json; charset=utf-8'); // set this header in json
    @mysql_close($conn);
    //echo json_encode($json);
   
    echo (json_encode($json,JSON_UNESCAPED_UNICODE));

// add this JSON_UNESCAPED_UNICODE in json output

Below are the steps show what changes we have to made in our query

Step 1:

Change database field Structure.

open Table fileld Structure and change in collation set there "utf8-general_ci". Below is screenshot

Step 2:

set mysql_quey before fire query

mysql_query ("set character_set_results='utf8'"); 

Step 3:

header('Content-Type: application/json; charset=utf-8'); // set this header in json

If we want this in html then we can use

header ('Content-type: text/html; charset=utf-8'); ?> 

also you can use


in html use echo $r['name']; it get in multi langage

Step 4:

After end of json return json_encode your rensponse with JSON_UNESCAPED_UNICODE

like this

echo (json_encode($json,JSON_UNESCAPED_UNICODE));

Hope this post will helpful for you :)

HTML/CSS- Design select boxes

Below are some useful select boxes designed using CSS and HTML, which are very useful in web desining

Follwing few simple steps, we can give good look and feel to checkboxes. Steps are as follows.

Step 1: Use below HTML









Step 2: Use below CSS

#design1 {
 background: none repeat scroll 0 0 steelblue;
 border: 1px solid;
 outline: medium none;
 overflow: hidden;
 width: 10%;
}

#design2 {
 background: none repeat scroll 0 0 transparent;
 border: 0 none;
 color: #eee;
 font-size: 20px;
 font-weight: bold;
 padding: 2px 10px;
 width: 378px;
 background-color: #58B14C;
 border-radius: 25px;
}

#design3 {
 background: none repeat scroll 0 0 transparent;
 border: 0 none;
 color: #eee;
 font-size: 20px;
 font-weight: bold;
 padding: 2px 10px;
 width: 378px;
 background-color: black;
 border-radius: 25px;
 background-image: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6));
}

#design4 {
 background-position: 97% center;
 background-repeat: no-repeat;
 border: 1px solid #aaa;
 color: #555;
 font-size: inherit;
 margin: 20px;
 overflow: hidden;
 padding: 5px 10px;
 text-overflow: ellipsis;
 white-space: nowrap;
 width: 300px;
}

#design5 {
 background-color: #A2AB58;
 background-position: 300px;
 background-repeat: no-repeat;
 border-radius: 5px;
 box-shadow: inset 0 0 10px 0 rgba(0, 0, 0, 0.6);
 color: #ff0;
 font-family: Cursive;
 font-size: 20px;
 line-height: 1;
 margin-top: 8px;
 outline: none;
 padding: 12px;
 webkit-appearance: none;
 width: 353px;
}

#design5:hover {
 color: #00ff7f;
}

Output









Hope this post will be useful for you :)

PHP- Generate random 5 characters string

We can do this using vey easy code. Below is the code to nerate random 5 characters string.

 
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
				 .'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
				 .'0123456789!@#$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];

echo $rand;

Magento 1.9 - Add "Scroll To Top" Button in Magento

Blow are the easy steps to add "Scroll To Top" Button in Magento website.

Step-1 Add this Div in footer.phtml

 

Step-2 Add this Java script in footer.phtml

 
jQuery(function() {
 jQuery(window).scroll(function() {
 if(jQuery(this).scrollTop() > 300) {
  jQuery('#back_top').fadeIn();   
 } else {
  jQuery('#back_top').fadeOut();
 }
});
   jQuery('#back_top').click(function() {
 jQuery('body,html').animate({scrollTop:0},500);
});   
});

Step-3 Add this CSS in theme's style.css

 
    #back_top {
    background-color: red;
    bottom: 22px;
    cursor: pointer;
    display: none;
    height: 44px;
    position: fixed;
    right: 200px;
    width: 54px;
}

Wordprss- Add "Scroll To Top" button in WordPress

Blow are the easy steps to add "Scroll To Top" button in WordPress website.

Step-1 Add this Div in footer.php

 

Step-2 Add this Java script in footer.php

 
jQuery(function() {
 jQuery(window).scroll(function() {
 if(jQuery(this).scrollTop() > 300) {
  jQuery('#back_top').fadeIn();   
 } else {
  jQuery('#back_top').fadeOut();
 }
});
   jQuery('#back_top').click(function() {
 jQuery('body,html').animate({scrollTop:0},500);
});   
});

Step-3 Add this CSS in theme's style.css

 
    #back_top {
    background-color: red;
    bottom: 22px;
    cursor: pointer;
    display: none;
    height: 44px;
    position: fixed;
    right: 200px;
    width: 54px;
}

wordpress-Change upload directory in worpress

let's say you upload a picture. After you upload it, you can view the file at something like:

 
example.org/wp-content/uploads/2014/12/picture.png

And let's say you now change the uploads folder location via: Now you need to change in wp-config.php

 
define('UPLOADS', 'wp-content/media');
This will give you a URL like this:
 
example.org/wp-content/media/2014/12/picture.png

Hope this will help!

WordPress - How can we create a "Custom Meta-box With Color Picker"?

Blow are the easy steps to create a custom meta-box with color picker in WordPress.
Step 1 – Register Custom Meta-box
 
function aft_add_meta_box() {
    add_meta_box('aft_sectionid', 'Post Background', 'aft_meta_box_callback', 'post');
}

add_action( 'add_meta_boxes', 'aft_add_meta_box' );
Step 2 – Creating Custom Metabox
 
function aft_meta_box_callback( $post ) {
    wp_nonce_field( 'aft_meta_box', 'aft_meta_box_nonce' );
    $color = get_post_meta( $post->ID, 'country_bg_color', true );
    ?>
    
    

<?php }
Step 3 –Saving Metabox
 
function aft_save_meta_box_data( $post_id ) {
    if ( !isset( $_POST['aft_meta_box_nonce'] ) ) {
        return;
    }

    if ( !wp_verify_nonce( $_POST['aft_meta_box_nonce'], 'aft_meta_box' ) ) {
        return;
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( !current_user_can( 'edit_post', $post_id ) ) {
        return;
    }
   
    $country_bg_color = ( isset( $_POST['country_bg_color'] ) ? sanitize_html_class( $_POST['country_bg_color'] ) : '' );
    update_post_meta( $post_id, 'country_bg_color', $country_bg_color );
}
add_action( 'save_post', 'aft_save_meta_box_data' );

Magento 1.9 - Custom RWD default magento slider

Custom RWD default magento slider

Below are the simple scripts steps

HTML

 
 
Previous Next

CSS

.slideshow-pager {
-moz-user-select: none;
overflow-x: hidden;
overflow-y: hidden;
position: absolute;
text-align: center;
top: auto;
width: 100%;
z-index: 115;
}
.slideshow-pager span {
color: #dddddd;
cursor: pointer;
display: inline-block;
font-family: "Roboto",sans-serif;
height: 10px;
width: 10px;
}
.slideshow-pager span:before {
background-color: #ccc;
border-radius: 10px;
content: "";
display: block !important;
height: 8px;
left: 50%;
margin-left: -8px;
margin-top: -8px;
position: relative;
top: 50%;
width: 8px;
}
.slideshow-pager span:hover:before {
background-color: #fff;
border:1px #999 solid;
}
.slideshow-pager span.cycle-pager-active:before {
background-color: #fff;
border:1px #999 solid;
}
.slideshow-pager > * {
cursor: pointer;
}

JS

        
$j(document).ready(function () {
  $j('.slideshow-container-pop .slideshow').cycle({
  slides: '> li',
  pager: '.slideshow-pager',
  pagerTemplate: '',
  speed: 600,
  pauseOnHover: true,
  swipe: true,
  prev: '.slideshow-prev',
  next: '.slideshow-next',
  fx: 'scrollHorz',
  timeout: 0
 });  
});

WORDPRESS- Replacing a textarea with WordPress TinyMCE wp_editor()

we can replace a textarea with WordPress TinyMCE wp_editor()

$content= 'default content';
$editor_id ='textarea_id';
$settings = array( 'textarea_name' => 'post_text' );
wp_editor( $content, $editor_id, $settings );

Wordpress- How to Create Custom Controls/textarea for the WordPress Theme Customizer

If we want to add ttwo textareas under Theme Customizer, we use the below code.

Put the below code in theme's function.php

/*Customizer1 Code HERE*/
add_action('customize_register', 'theme_bannertext1_customizer' , 11);
function theme_bannertext1_customizer($wp_customize){
 //adding section in wordpress customizer  
    $wp_customize->add_section('banne1_settings_section', array(
      'title'          => 'Banner Text 1'
     ));
    //adding setting for footer text area
    $wp_customize->add_setting('banne1_settings_section', array(
     'default'        => 'Modern Axure template for Beautiful prototypes',
     ));
    $wp_customize->add_control('banne1_settings_section', array(
     'label'   => 'Banner Text1 Here',
      'section' => 'banne1_settings_section',
     'type'    => 'textarea',
    ));

}

 
 
/*Customizer2 Code HERE*/
add_action('customize_register', 'theme_bannertext2_customizer' , 12);
function theme_bannertext2_customizer($wp_customize){
 //adding section in wordpress customizer  
    $wp_customize->add_section('banne2_settings_section', array(
      'title'          => 'Banner Text 2'
     ));
    //adding setting for footer text area
    $wp_customize->add_setting('banne2_settings_section', array(
     'default'        => 'Modern Axure template for Beautiful prototypes',
     ));
    $wp_customize->add_control('banne2_settings_section', array(
     'label'   => 'Banner Text1 Here',
      'section' => 'banne2_settings_section',
     'type'    => 'textarea',
    ));

 }
 

Magento 1.9- Magento Sort Attribute by Decimal not Alphanumerically

The best solution I found was to override the ORDER BY for the query by calling a primitive method of the Collection class, here's the example they give:

$_productCollection = Mage::getModel('catalog/product')->getCollection();
$_productCollection->setOrder('weight', 'asc');
$_productCollection->getSelect()->reset(Zend_Db_Select::ORDER);
$_productCollection->getSelect()->order('CAST(`weight` AS SIGNED) ASC'));

PHP- check if image exists php

Question: How can we check if image exists with php code?

Answer: Below is the code to check if image exists or not.

if (getimagesize($user_profilr_pic_url) !== false) {
  echo 'Image Exist';
}else{
  echo 'Image Does Not Exist';
}

Wordpress- How to use AJAX in WordPress

Below are easy steps to use AJAX in WordPress

STEP 1. Put the below code in your template file.

HTML

Click Here to Ajax Request/response 

Script

var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";

Script

jQuery(document).ready(function($) {   
 jQuery('#click_to_ajax').click(function() {
    
  var par1 = 'Banana';
  var par2 = 'Mango';
    
    jQuery.ajax({
   url: ajaxurl,
   data: {
    'action':'my_action_name',
    'par_1' : par1,
    'par_2' : par2,
   },
   success:function(data) {
     //console.log(data);
     alert(data);
   },
   error: function(errorThrown){
    //console.log(errorThrown);
     alert('Something is wrong');
   }
  });       
 });    
});

STEP 2. Put the bellow code in functions.php in your theme file.

function my_ajax_callback_function()
{

    print_r($_REQUEST);
}
   
add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );    // If called from admin panel
add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );    // If called from front end

STEP 3. Make sure jquery libarary has been included for the page.

Magento 1.9 : Get Current Currency Symbol

Code is useful for get currency symbol

Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();

or if you want to pass a certain currency code simply specify it:

Mage::app()->getLocale()->currency('EUR')->getSymbol();

PHP- Create slug from string

Below is simple function to slug from string.

Code

function create_slug($string){
   $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
   return $slug;
}
echo create_slug('does this thing work or not');
//returns 'does-this-thing-work-or-not'

Output

does-this-thing-work-or-not

Wordpress- set featured image in normal position

Below is the filter to set featured image in normal position . This is very simple code.

add_action('do_meta_boxes', 'featured_image_move_meta_box');
function featured_image_move_meta_box(){
    remove_meta_box( 'postimagediv', 'post', 'side' );
    add_meta_box('postimagediv', __('Carousel Image'), 'post_thumbnail_meta_box', 'post', 'normal', 'high');
}

WordPress- add feature Image column in WP Admin for custom posts /post/page

Below are the simple steps to add feature Image column in WP Admin for custom post/post/page

1. Add the posts and pages columns filter. They can both use the same function.

add_filter('manage_posts_columns', 'tcb_add_post_thumbnail_column', 5);
add_filter('manage_pages_columns', 'tcb_add_post_thumbnail_column', 5);
add_filter('manage_custom_post_columns', 'tcb_add_post_thumbnail_column', 5);

2. Add the column

function tcb_add_post_thumbnail_column($cols){
$cols['tcb_post_thumb'] = __('Featured Image');
return $cols;
}

3. Hook into the posts an pages column managing. Sharing function callback again.

add_action('manage_posts_custom_column', 'tcb_display_post_thumbnail_column', 5, 2);
add_action('manage_pages_custom_column', 'tcb_display_post_thumbnail_column', 5, 2);
add_action('manage_custom_post_column', 'tcb_display_post_thumbnail_column', 5, 2);

4.bGrab featured-thumbnail size post thumbnail and display it.

function tcb_display_post_thumbnail_column($col, $id){
 switch($col){
 case 'tcb_post_thumb':
   if( function_exists('the_post_thumbnail') )
   echo the_post_thumbnail( 'featured-thumbnail' );

   else
  echo 'Not supported in theme';
   break;
 }
}

Mysql- How can I access the MySQL command line with XAMPP for Windows?

Follow the following steps-

Step 1:
Open command prompt














Step 2:
cd c:\xampp\mysql\bin
Step 3:
mysql.exe -u root 

CSS- Simple popup through css

Blow is the code for popup through css

CSS

.blankdiv{
 background-color:#000;
 position:fixed;
 z-index: 9001;
 top:0px; height:100%;
 left:0px;
 width:100%; opacity: 0.65;
 filter:alpha(opacity=65);
}

#popupform{
    height: 100%;
    left: 0;
    padding: 15px;
    position: fixed;
    top: 0;
    width:97%;
    z-index: 10001;
}
  
#popupform .applyform{
 position:relative; overflow:auto;
 background-color:#fff;
 width:670px;
 height:500px;  margin:5% auto auto auto;
 z-index: 9002; padding:10px; border:10px solid #7F3814;
}


#pclose{
    background-position: left top;
    background-repeat: no-repeat;
    cursor: pointer;
    height: 25px;
    margin: 5% auto -6%;
    position: relative;
    right: -324px;
    top: 24px;
    width: 25px;
    z-index: 9999;
}

HTML

Click Me

Magento 1.9 - how to create layout of custom controller in magento

1. First create a controller. Suppose controller name is "test". put this code here action name is "name".

class namespace_modulename_TestController extends Mage_Core_Controller_Front_Action{
public function nameAction()
{
    $this->loadLayout();  
   $this->renderLayout();
   
}
}

2. After controller creation set layout go to design->template->layou open the xml file put these code

 
    
        
        
      
        
      

3. and last send request for controller "modulname/controller/actionname". print the all data of test.phtml file.

Magento 1.9 - Create custom home page layout in magento

Create custom home page layout in magento

1.) First go to app/design/frontend/rwd/default/layout/page.xml and following code after one_page colamn structure


 
 
  
  
  1
  home
 

2.) second open app/code/core/Mage/Page/etc/config.xml file and set following code after one_page colamn


 
 
 page_home
 1

3.) And last go to admin->cms->pages in content tab select your home page.

Magento 1.9 - Change page layout from controller

You need to replace one line of code in your controller where you want to change the layout of the page if you are not able to do from xml through setlayout.

Replace

$this->loadLayout(); 

with

$this->loadLayout()->getLayout()->getBlock('root')->setTemplate('page/1column.phtml'); 

Wordpress-Using wpdb to connect to a separate database

Below is the code to connect to a separate database in wordpress.

$mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("select Name from my_table");
echo "
    "; foreach ($rows as $obj) : echo "
  • ".$obj->Name."
  • "; endforeach; echo "
";

Wordpress- Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

Question:

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

Answer:

OK, I fixed it.

I added this to my wp-config.php:

define( 'DB_CHARSET', 'utf8' );
define( 'DB_COLLATE', 'utf8_general_ci' );

Worked for me!

PHP - random string generate in php

Below is very easy function to generate random string in php.
function Password_genrator($length = 10) {
    $characters = '0123456789!@#$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

echo Password_genrator();

Magento 1.9 - Mysql query to get all products images count in particular category

Mysql query to get all products images count in particular category

 
Below is mysql query to get all products images count in particular category
select count(*) from `catalog_product_entity_media_gallery` as t1 join `catalog_category_product` as t2 on t1.entity_id = t2.product_id
where t2.category_id = 3  and t1.attribute_id=88

PHP- What are the different errors in PHP?

What are the different errors in PHP?

 In PHP, there are three types of runtime errors, they are:

 Warnings:
These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user by default but they will not result in ending the script.

Notices:
These errors are non-critical and trivial errors that come across while executing the script in PHP. Example: trying to gain access the variable which is not defined. These errors are not showed to the users by default even if the default behavior is changed.  

Fatal errors:
 These are critical errors. Example: instantiating an object of a class which does not exist or a non-existent function is called. These errors results in termination of the script immediately and default behavior of PHP is shown to them when they take place. Twelve different error types are used to represent these variations internally.

Magento 1.9 - Features use of Magento

Features use of Magento

1. One of the most amazing features about Magento is that you can design and develop multiple web sites and they store and share one administrative interface. This extremely flexible feature allows you to modify and control multiple web sites. All of your products inventory and pricing can be controlled from one central location. There is no longer a need to login to multiple locations to handle multiple web sites. Magento has the ability to control them all.

2. Magento supports over sixty languages, multiple currencies, and tax rates. This gives you the ability to easily expand in the global market.

3. Layered navigation gives users customized browsing options when viewing products by categories. You can now sort products by price, size, color, and other customizable attributes.
4. Magento also has built-in web services. This flexibility allows external applications to access magento’s data without changing the underlying core code. Currently, SOAP and XML-RPC protocols are available out of the box.

5. Magento has Search Engine Optimization (SEO) built in from the start. It has the ability to handle friendly URL rewrites which make it easy for search engines to index your store and products.

6. Not only does Magento offer real-time carrier rates and quotes, users can ship products from one order to multiple shipping address. This makes gift shopping especially easy.

7. Magento also has several reporting features built in. These allows for easy view of sales reports, best-selling products, and customer reporting. They can even be exported in a CSV format to integrate with excel and other database programs.

8. Magento has designed its file structure to three major sections: core, functionality, and design. This allows for easy updating of images and CSS styling without affecting the functionality of the site. Store functionality can also be easily customized without affecting the Magento’s core. As a result, you can modify Magento without having to worry about upgrading to newer versions in the future.

9. Magento has a huge community backing. In addition to a public forum and bug tracking, Magento also has its own public repository of extensions called Magento Connect. Magento Connect features both free and commercial extensions to enhance the functionality of your web site.

10. Since Magento is released under the Open Software License (OSL), the Magento Community Edition is available at no cost. In turn, this allows web site developers and eCommerce web site owners to cut down on software costs.

Javascript/jQuery - confirmation dialog on href-link

By Inline event handler

In the most simple way, we can use the confirm() function in an inline onclick handler.

Link
Using Advanced event handling

But normally we would like to separate HTML and Javascript, so we don't use inline event handlers, but put a class on our link and add an event listener to it.
Link
    var elems = document.getElementsByClassName('confirmation');
    var confirmIt = function (e) {
        if (!confirm('Are you sure?')) e.preventDefault();
    };
    for (var i = 0, l = elems.length; i < l; i++) {
        elems[i].addEventListener('click', confirmIt, false);
    }
By jQuery

Just for fun, here is how this would look with jQuery
Link
    $('.confirmation').on('click', function () {
        return confirm('Are you sure want to delete this item?');
    });

Google Map- How to add Google Maps Autocomplete search box?

Topic:

How to add Google Maps Autocomplete search box?

Solution:

Below are the steps and code.

Include google library.


HTML


SCRIPT

function initialize() {

var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}

google.maps.event.addDomListener(window, 'load', initialize);

JavaScript - Fullscreen API JavaScript Code

Topic:

Fullscreen API JavaScript Code

Solution:

Blow are the scripts.

HTML:


JS:
function toggleFullscreen(elem) {
  elem = elem || document.documentElement;
  if (!document.fullscreenElement && !document.mozFullScreenElement &&
    !document.webkitFullscreenElement && !document.msFullscreenElement) {
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.msRequestFullscreen) {
      elem.msRequestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
      elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  }
}

document.getElementById('btnFullscreen').addEventListener('click', function() {
  toggleFullscreen();
});

document.getElementById('exampleImage').addEventListener('click', function() {
  toggleFullscreen(this);
});

/*
if (document.addEventListener)
{
    document.addEventListener('webkitfullscreenchange', exitHandler, false);
    document.addEventListener('mozfullscreenchange', exitHandler, false);
    document.addEventListener('fullscreenchange', exitHandler, false);
    document.addEventListener('MSFullscreenChange', exitHandler, false);
}

function exitHandler()
{
  if (!document.fullscreenElement && !document.mozFullScreenElement &&
        !document.webkitFullscreenElement && !document.msFullscreenElement) {
      jQuery('.click-to-full-scr').html('Full Screen');
      jQuery('#toPopup_photodet').removeClass('done-fullscreen');
  }
}*/

Magento- Country and States in Magento

Topic:

How can we get Country and States in Magento?

Solution:

Magento has inbuilt model for Country and State as seen in Checkout page. In checkout page if you select Country like ‘France’ , a drop down will be seen in place of textbox for States. I am writing here the code to directly get country name from ID and also to get States info from country.

    $countryName = Mage::getModel('directory/country')->load('FR')->getName(); //get country name
 
     
    echo 'Country Name ->'.$countryName.'
'; $states = Mage::getModel('directory/country')->load('FR')->getRegions(); //state names foreach ($states as $state) { echo 'ID->'.$state->getId().'
'; echo 'Name->'.$state->getName().'
'; }

Wordpress - localhost url not found

Topic:

Wordpress - localhost url not found

Solution:

we have to follw the following steps.

you will need to edit the http.conf file in the Apache -> Conf folder

1. Open in a plain text editor

2. Find the line that looks like this

#LoadModule rewrite_module modules/mod_rewrite.so

3. Remove hash

LoadModule rewrite_module modules/mod_rewrite.so

4. save

5. regenerate .htaccess

Enjoy :)

Javascript: Download PDF using javascript

Topic:

Download PDF using javascript

Solution:

Below is the script which will help in Download PDF.

var x= 'http://your-site/pdf-report/purchasing-report.pdf'; //PDF URL
myTempWindow = window.open(x,'','left=10000,screenX=10000');
myTempWindow.document.execCommand('SaveAs','null','download.pdf');

Wordpress- How to Change the Login page Logo URL in WordPress

Topic:

How can we change the Login page Logo URL in WordPress?

Solution:

Using below action we change the Login page Logo URL .

add_filter( 'login_headerurl', 'custom_loginlogo_url' );
function custom_loginlogo_url($url) {
    return 'http://www.your-site-url.com';
}

WordPress- How to Change the Login page Logo in WordPress

Topic:

How can we change the Login page Logo in WordPress?

Solution:

Using below action we change the Login page Logo.

function custom_loginlogo() {
echo '';
}
add_action('login_head', 'custom_loginlogo');

WooCommerce – remove payment method from emails

Topic:

How can we remove payment method from emails in woocommerce using a filter?

Solution:

Using below filter we can remove payment method from emails.

add_filter( 'woocommerce_get_order_item_totals', 'custom_woocommerce_get_order_item_totals' );

function custom_woocommerce_get_order_item_totals( $totals ) {
  unset( $totals['payment_method'] );
  return $totals;
}

Wordpress- Delete users between two registration dates programatically

How can we delete user between two registration dates programatically in wordpress?

Solution:

 
function get_users_registered_between_date($start='', $end='' ){
     global $wpdb;
     $prefix =$wpdb->prefix;
     $user_table= $prefix.'users';
     
     if( empty($start) )
          $date = date('Y-m-d');

     if ( empty($end) )
          $end = $start;

     $start_dt = new DateTime($start. ' 00:00:00');
     $s = $start_dt->format('Y-m-d H:i:s');

     $end_dt = new DateTime($end.' 23:59:59');
     $e = $end_dt->format('Y-m-d H:i:s');
   
     $sql = $wpdb->prepare("SELECT ID FROM $user_table WHERE 1=1 AND CAST(user_registered AS DATE) BETWEEN %s AND %s ORDER BY user_login ASC",$s,$e);
     $users = $wpdb->get_results($sql);

     return $users;
}



$start_date='2015-02-14';  // registration date
$end_date='2015-04-17';  // registration date
$users= get_users_registered_between_date($start_date, $end_date ); // users list between date  '2015-02-14' and '2015-04-17'

require_once(ABSPATH.'wp-admin/includes/user.php' );
foreach($users as $usr){
    $user_id= $usr->ID;
    $roles= array();
    $user = get_userdata( $user_id );
    $capabilities = $user->{$wpdb->prefix . 'capabilities'};

    if ( !isset( $wp_roles ) )
        $wp_roles = new WP_Roles();

    foreach ( $wp_roles->role_names as $role => $name ) :

        if ( array_key_exists( $role, $capabilities ) )
            $roles[]=$role;

    endforeach;
   
    if (!in_array("administrator", $roles)) {
       if(wp_delete_user($user_id)){
        echo 'User deleted'.$user_id;
        echo '
'; } } }

Wordpress- Delete user programatically

How can we delete user programatically in wordpress?

Solution:

 
global $wpdb;
$curr_date= date('Ymd');

require_once(ABSPATH.'wp-admin/includes/user.php' );
$users = get_users(array(
    'meta_key'     => 'user_delete_date',
    'meta_value'  => "$curr_date",
));

foreach($users as $usr){
    $user_id= $usr->ID;
    $roles= array();
    $user = get_userdata( $user_id );
    $capabilities = $user->{$wpdb->prefix . 'capabilities'};

    if ( !isset( $wp_roles ) )
        $wp_roles = new WP_Roles();

    foreach ( $wp_roles->role_names as $role => $name ) :

        if ( array_key_exists( $role, $capabilities ) )
            $roles[]=$role;

    endforeach;
  
    if (!in_array("administrator", $roles)) {
       if(wp_delete_user($user_id)){
        echo 'User deleted'.$user_id;
        echo '
'; } } }

Disable Right Click

Script:
 
document.onmousedown=disableclick;
status="Right Click Disabled";
Function disableclick(event)
{
  if(event.button==2)
   {
  alert(status);
  return false;    
   }
}
HTML:

<body oncontextmenu="return false">
...
</body>

HTML/JS-Tabs with fade in /fade out effect using jQuery

HTML:

 

 
 
Tab1 content

SCRIPT:

 

function ShowHideTab(current){
 jQuery( ".tab-listing" ).each(function( index ) {
 var toshow= index+1;
  if(current==toshow){
  jQuery('#show_hide_'+toshow).fadeIn(1000);
  }else{
  jQuery('#show_hide_'+toshow).fadeOut(1000);
  }
 });
}

jQuery(document).on('click', '.tab-cat-name li a', function() {
   jQuery(".tab-cat-name li a").removeClass("active");
   jQuery(this).addClass("active");
});   

Note: Please make sure, jQuery libary has been included for the page.

Wordpress- Custom columns for custom post types

Step 1. Adding custom columns-

The first step in creating custom columns, is to make these columns available on the edit posts page. WordPress has a variable filter hook for this called manage_edit-{$post_type}_columns for all post types. Since the name of our post type is movie, the name of the hook you’d use is manage_edit-movie_columns.

What we’ll do here is overwrite all of the default columns and set it up however we want. In this example, we’re using five columns:

1. cb: The checkbox column.

2. title: The post title column, which we’re changing to read “Movie.”

3. duration: The column for the duration of the movie (custom metadata).

4. family: The column for the movie family (custom taxonomy).

5. date: The default post date column.

Filtering these columns is fairly simple. You only need to return an array of key/value pairs. The key is the column name and the value is the output of the column header/label.

 
add_filter( 'manage_edit-movie_columns', 'my_edit_movie_columns' ) ;

function my_edit_movie_columns( $columns ) {

    $columns = array(
        'cb' => '',
        'title' => __( 'Movie' ),
        'duration' => __( 'Duration' ),
        'family' => __( 'Family' ),
        'date' => __( 'Date' )
    );

    return $columns;
}

Step 2.Adding content to custom columns

The action hook in this case is manage_{$post_type}_posts_custom_column. Remember, the name of the post type is movie, so this hook becomes manage_movie_posts_custom_column.

 
add_action( 'manage_movie_posts_custom_column', 'my_manage_movie_columns', 10, 2 );

function my_manage_movie_columns( $column, $post_id ) {
    global $post;

    switch( $column ) {

        /* If displaying the 'duration' column. */
        case 'duration' :

            /* Get the post meta. */
            $duration = get_post_meta( $post_id, 'duration', true );

            /* If no duration is found, output a default message. */
            if ( empty( $duration ) )
                echo __( 'Unknown' );

            /* If there is a duration, append 'minutes' to the text string. */
            else
                printf( __( '%s minutes' ), $duration );

            break;

        /* If displaying the 'family' column. */
        case 'family' :

            /* Get the familys for the post. */
            $terms = get_the_terms( $post_id, 'family' );

            /* If terms were found. */
            if ( !empty( $terms ) ) {

                $out = array();

                /* Loop through each term, linking to the 'edit posts' page for the specific term. */
                foreach ( $terms as $term ) {
                    $out[] = sprintf( '%s',
                        esc_url( add_query_arg( array( 'post_type' => $post->post_type, 'family' => $term->slug ), 'edit.php' ) ),
                        esc_html( sanitize_term_field( 'name', $term->name, $term->term_id, 'family', 'display' ) )
                    );
                }

                /* Join the terms, separating them with a comma. */
                echo join( ', ', $out );
            }

            /* If no terms were found, output a default message. */
            else {
                _e( 'No familys' );
            }

            break;

        /* Just break out of the switch statement for everything else. */
        default :
            break;
    }
}

Step 3. (If you want to ) Making custom columns sortable

The first step is making the duration column sortable by filtering the manage_edit-{$post_type}_sortable_columns hook as shown in the following code.

 
add_filter( 'manage_edit-movie_sortable_columns', 'my_movie_sortable_columns' );

function my_movie_sortable_columns( $columns ) {

    $columns['duration'] = 'duration';

    return $columns;
}



/* Only run our customization on the 'edit.php' page in the admin. */
add_action( 'load-edit.php', 'my_edit_movie_load' );

function my_edit_movie_load() {
    add_filter( 'request', 'my_sort_movies' );
}

/* Sorts the movies. */
function my_sort_movies( $vars ) {

    /* Check if we're viewing the 'movie' post type. */
    if ( isset( $vars['post_type'] ) && 'movie' == $vars['post_type'] ) {

        /* Check if 'orderby' is set to 'duration'. */
        if ( isset( $vars['orderby'] ) && 'duration' == $vars['orderby'] ) {

            /* Merge the query vars with our custom variables. */
            $vars = array_merge(
                $vars,
                array(
                    'meta_key' => 'duration',
                    'orderby' => 'meta_value_num'
                )
            );
        }
    }

    return $vars;
}

Enjoy :)

Magento 1.9- Display Most Viewed Products

Create a file app/code/local/Mage/Catalog/Block/Product/Mostviewed.php and add the following lines of code in it.

 
class Mage_Catalog_Block_Product_Mostviewed 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)
            ->addViewsCount();
        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);

        $products->setPageSize(5)->setCurPage(1);
        $this->setProductCollection($products);
    }
}
Step 2:

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

 
<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<?php echo $this->__('These Products Are Popular Right Now!') ?>
<?php $_collectionSize = 5;//count($_products->getItems()); echo $_collectionSize; ?>
    <?php $i=1; foreach ($_products->getItems() as $_product): ?>
  • <?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>

    <?php echo $this->htmlEscape($_product->getName()) ?>

    <?php if($_product->getRatingSummary()): ?> <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?> <?php endif; ?> <?php echo $this->getPriceHtml($_product, true) ?> <?php if($_product->isSaleable()): ?>
    <?php else: ?>

    <?php echo $this->__('Out of stock') ?>

    <?php endif; ?>
  • <?php $i++; endforeach; $kol = $_collectionSize; ?>
<?php endif; ?>
Step 3:

Now, we have the code in place which will fetch the most viewed products on call. Still, we need to add a block to show most viewed products in a desired location.

 
{{block type="catalog/product_mostviewed" template="catalog/product/mostviewed.phtml"}}

Magento 1.9 - Display Best Selling Products

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()): ?>

<?php echo $this->__('Best Seller Products') ?>

<?php $_collectionSize = count($_products->getItems()) ?> <?php $i=1; foreach ($_products->getItems() as $_product): ?> <?php if ($i%1!==0): ?> <?php endif ?> <?php if ($i%3==0 or $i==$_collectionSize): ?> <?php endif ?> <?php $i++; endforeach; $kol = $_collectionSize; ?>
<?php contentBlock('top') ?>

<?php echo $this->htmlEscape($_product->getName()) ?>

<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>
<?php if($_product->getRatingSummary()): ?> <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?> <?php endif; ?> <?php echo $this->getPriceHtml($_product, true) ?> <?php if($_product->isSaleable()): ?>
<?php else: ?>

<?php echo $this->__('Out of stock') ?>

<?php endif; ?> <?php if($_product->getevent_date()) {echo $_product->getevent_date();} ?>
<?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"}}

Magento 1.9 - My first simple module to print "Hello Aftab !"

Below are the steps to create module to print "Hello Aftab !"
Step 1. Create: app/etc/modules/Aftab_Hello.xml put:
<xml version="1.0"?>

    
        
        true
        local
        
    

Step2. Create: app/code/local/Aftab/Helloaftab/config.xml Put:
<?xml version="1.0"?>

    
        
            0.1.0
        
    
    
        
            
                standard
                
                    Aftab_Helloaftab
                    helloaftab
                
            
        
       
        
            
                
                    helloaftab.xml
                
            
        
    
    
            
                
                    Aftab_Helloaftab_Block
                
            
    

Step3. Create: app/code/local/Aftab/Helloaftab/controllers/IndexController.php Put:
class Aftab_Helloaftab_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        //echo "Hello Aftab !";
        $this->loadLayout();
        $this->renderLayout();
    }
   
    public function arshadAction()
    {
        //echo "Hello  Arshad !";
        $this->loadLayout();
        $this->renderLayout();
    }
}
Step 4. Create: app/code/local/Aftab/Helloaftab/Block/helloaftab.php Put:
class Aftab_Helloaftab_Block_Helloaftab extends Mage_Core_Block_Template
{
   
}
Step 5. Create: app/design/frontend/YOUR_THEME_PACKAGE/YOUR_THEME/layout/helloaftab.xml Put:

    
        
            
        
    

Step 6. Create: app/design/frontend/YOUR_THEME_PACKAGE/YOUR_THEME/template/helloaftab/helloaftab.phtml Put:
 echo "Hello Aftab !"; 
Step 7. http://you-site-url/helloaftab/index/ Or http://you-site-url/helloaftab/index/index

Wordpress-What are hooks and define types of hooks in WordPress?

Hooks are provided by WordPress to allow your plugin to 'hook into' the rest of WordPress, i.e., to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two kinds of hooks:

Actions Hooks: Actions hooks are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Your plugin can specify that one or more of its PHP functions which are executed at these points, using the Action API.

Filters Hooks: Filters hooks are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen. Your plugin can specify that one or more of its PHP functions which are executed to modify specific types of text at these times, using the Filter API.

Actions Function Examples:
has_action()
add_action()
do_action()
do_action_ref_array()
did_action()
remove_action()
remove_all_actions()

Filter Function Examples:
has_filter()
add_filter()
apply_filters()
apply_filters_ref_array()
current_filter()
merge_filters()
remove_filter()
remove_all_filters()

jQuery-Add/Remove Input Fields Dynamically with jQuery

Below is the tested code to Add/Remove Input Fields Dynamically with jQuery

HTML:

 

Script:

 
jQuery(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = jQuery(".input_fields_wrap"); //Fields wrapper
    var add_button      = jQuery(".add_field_button"); //Add button ID
  
    var x = 1; //initlal text box count
    jQuery(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            jQuery(wrapper).append(''); //add input box
        }
    });
  
   jQuery(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); jQuery(this).parent('div').remove(); x--;
   })
});

Note: Make sure, jQuery library has been included for the page.

Enjoy the day :) :)

JQuery- hide a DIV when the user clicks outside of it

Topic:

Hide a DIV when the user clicks outside of it, anywhere on body.

Solution:

HTML

  


Script

 
jQuery(document).ready(function() {
    jQuery("#label-search").click(function(e) {
        jQuery("#search").show();
        jQuery("#label-search").hide();
        e.stopPropagation();
    });

    jQuery(document).click(function(e) {
        if (!jQuery(e.target).is('#label-search, #search')) {
            jQuery("#search").hide();
            jQuery("#label-search").show();
        }
    });
});

Note: Make sure, jQuery library has been included for the page.

Enjoy the day :) :)

Ajax- Submit Form Using Ajax Simple Example

Below is simple code for htmt and jQuey script.

HTML Code

 
First Name:
Last Name:
Email :

Script

 

jQuery("#ajaxform").submit(function(e)
{
 var postData = jQuery(this).serializeArray();
 var formURL = jQuery(this).attr("action");
 jQuery.ajax(
 {
  url : formURL,
  type: "POST",
  data : postData,
  success:function(data, textStatus, jqXHR) 
  {

  },
  error: function(jqXHR, textStatus, errorThrown) 
  {
  }
 });
    e.preventDefault(); //STOP default action
}); 

Note: Please be sure, jQuery library has included for the page.

Enjoy the day :) :)

jQuery- get multiple image's file name on browse image

Topic 1. jQuery- get multiple image's file name on browse image

Topic 2. How can I get file's name on browse the image?

Solution:

We can find above topic's solution in below code.

HTML:

 

SCRIPT:

 
jQuery("#inputFile").change(function (event) {
   var files = event.target.files;
    for(var i=0; i < files.length; i++) {
        var f = files[i];
        alert(f.name);
    }
});

Wordpress- Function to login- If user exists and Function to Register - If user does not exists

When we are submitting a form with fields username/email and password. We have to login if user exist and register as new user if there user does not exist.
Below is the code which will help to fulfill our requirement.
 
global $wpdb;
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];

// Function to login- If user exists     
if( email_exists( $email )) {
 $user = get_user_by( 'email', $email );
 $user_id= $user->ID;
  if ( $user && wp_check_password( $password, $user->data->user_pass, $user->ID) ){
  $secure_cookie = is_ssl();
  $secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array());
  global $auth_secure_cookie;
  $auth_secure_cookie = $secure_cookie;
   
  wp_set_auth_cookie($user_id, true, $secure_cookie);
  $user_info = get_userdata($user_id);
  do_action('wp_login', $user_info->user_login, $user_info);
   $msg= 'You are logged In successfully.';
  }else{
   $msg= 'Username / Password is wrong. Please try again.';
  }   
 exit($msg);       
   
}else{
  // Function to Register - If user does not exists
 $username = explode("@", $email);
 $username = sanitize_text_field( $username[0] );
 $email = sanitize_text_field(  $_REQUEST['email']  );
 $password = $wpdb->escape( sanitize_text_field( $password));
 $status = wp_create_user($username,$password,$email);
 
   
 $user_id=$status;
 update_user_meta( $user_id,'first_name', $username); //update user meta
   
 //autologin start
 $secure_cookie = is_ssl();
 $secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array());
 global $auth_secure_cookie;
 $auth_secure_cookie = $secure_cookie;
 wp_set_auth_cookie($user_id, true, $secure_cookie);
 $user_info = get_userdata($user_id);
 do_action('wp_login', $user_info->user_login, $user_info);
 //autologin end       

 exit('User is created successfully.');   

}

Wordpress- How to Customise Divi Thumbnail Sizes

Topic:

How can we customise Divi Thumbnail Sizes?

Solution:

To customise the index and archive page, as well as single post thumbnails using different filters.

Below is the code, you can just remove or comment out the filters if you don’t want to use them.

 
/**
 * Set blog, index, archive & post thumbnail sizes
 */


/* Blog */
function wpaft_blog_thumbnail_width( $width ) {
 return 150; //blog thumbnail width in pixels
}
add_filter( 'et_pb_blog_image_width', 'wpaft_blog_thumbnail_width');
function wpaft_blog_thumbnail_height( $height ) {
 return 150; //blog thumbnail height in pixels
}
add_filter( 'et_pb_blog_image_height', 'wpaft_blog_thumbnail_height');


/* Index & archive */
function wpaft_index_thumbnail_width( $width ) {
 if( !is_single() ) {
   return 150; //index thumbnail width in pixels
 } else {
  return $width;
 }
}
add_filter( 'et_pb_index_blog_image_width', 'wpaft_index_thumbnail_width');
function wpaft_index_thumbnail_height( $height ) {
 if( !is_single() ) {
  return 150; //index thumbnail height in pixels
 } else {
  return $height;
 }
}
add_filter( 'et_pb_index_blog_image_height', 'wpaft_index_thumbnail_height');


/* Post */
function wpaft_post_thumbnail_width( $width ) {
 if( is_single() ) {
   return 300; //post thumbnail width in pixels
 } else {
  return $width;
 }
}
add_filter( 'et_pb_index_blog_image_width', 'wpaft_post_thumbnail_width');
function wpaft_post_thumbnail_height( $height ) {
 if( is_single() ) {
  return 300; //post thumbnail height in pixels
 } else {
  return $height;
 }
}
add_filter( 'et_pb_index_blog_image_height', 'wpaft_post_thumbnail_height');

Magento 1.9- upload multiple files with Varien_File_Uploader

Topic 1: upload file with Varien_File_Uploader .

Topic 2: How can I upload image using Varien_File_Uploader in magento?

Topic 3: Upload image using default magento function.

We can find above topic's solution in below code.

 
 if(isset($_FILES['add_image']['name']) && $_FILES['add_image']['name'] != '') {
 try {
  /* Starting upload */
  $uploader = new Varien_File_Uploader('add_image');

  // Any extention would work
  $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
  $uploader->setAllowRenameFiles(false);

  $uploader->setFilesDispersion(true);

  // We set media as the upload dir
  $path = Mage::getBaseDir('media') . DS . 'projectphoto' . DS . 'image' . DS;
  $uploader->save($path, $_FILES['add_image']['name'] );
  echo '-->'.$img_name = $uploader->getUploadedFileName();
 } catch (Exception $e) {

 }
}
  

WordPress: How can we use WPDB Class To Connect and Fetch Data From Another Database?

How can we use WPDB Class To Connect and Fetch Data From Another Database?

Solution:

Let us say we have installed wordpress into the database wp_wordpress and we want to fetch some data from another independent database which has nothing to do with wordpress .

Here is how you can do it.

Query to Data Using WPDB

If we have used the wordpress global variable $wpdb before, querying for data is nothing different from what we have done previously.

Now, here is the trick. we have to instantiate a new WPDB instance.

 
$mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("select Name from my_table");
echo "
    "; foreach ($rows as $obj) : echo "
  • ".$obj->Name."
  • "; endforeach; echo "
";

The benefit is the ability to use all the wpdb classes and functions like get_results, etc so that there's no need to re-invent the wheel.