Monday, 10 December 2012

Youtube API tutorial PHP - Setup in xampp

In this blog We're gonna see how to set up youtube api environment in php xampp. Google clearly gives the documentation for this here. But still I'm stuck at the middle somewhere. Because I've never configured this before. So this is absolutely for beginners.

Download the Google Data Client Library files from the zend website, as we use Zend Gdata for Youtube API. We dont have to install zend framework for this to work. Just download Zend_Gdata from the above link which is located at the bottom of the Zend framework page.

Extract the folder and add the location of the library folder to your PHP path. We can set the path by 2 ways. One by using set_include_path() method and other by using setting path using php.ini file. For me it is located in C:\xampp\php. Open php.ini and search for include_path variable. I extracted Zend_Gdata in C:\xampp\ and rename the folder as ZendGdata.

Now edit the include_path variable by including this path C:\xampp\ZendGdata\library. Make sure there is a library folder in that path. Now restart your apache server and test whether the script works by going to this script. It is installation checker script for this. If all the scripts were passed then it'll show no errors found. I got one error when running this script. It is openssl error. We can solve it by uncommenting ;extension=php_openssl.dll to extension=php_openssl.dll in php.ini file and restarting the apache server. Then I got no errors.

Now run the demo files in the demo folder of Zend_Gdata folder(copy the demo folder to htdocs folder). Thats It! It'll work like charm!

 

Wednesday, 5 December 2012

How to use ajax using jQuery load method for appending data with fade in effect?

Usually we use $.ajax or $.post to use ajax in our script. But now we are gonna use load() to send ajax requests to server.

var offset = 0;   
$("#button").click(function(){      
        offset = offset+5;
    $("#morePosts").load("/post.php?offset="+offset, function(data) {   
    if($(data).is(':empty')){
            $(data).hide().appendTo('#morePosts').fadeIn("slow");           
    }else{
     $("#button").attr({"disabled":"disabled", "value":"No more posts to display"});   
    }
});
        return false;
});

I've used this in wordpress to load more posts in ajax. It'll display 5 posts each time when we click #button.

In the first parameter we are giving URL with offset as parameter to post.php(GET request).
Second parameter is the callback function used to get the data from the post.php after processing GET request.

 data is the returned data from post.php and we are checking whether the data is empty or not
using is(':empty') and appending that data to #morePosts div.

Then we are using appendTo() where we first hide the data and appending it to #morePosts div and then showing it by fadeIn()

If the data is empty we disable the button attribute using attr({"disabled":"disabled"}).

Thats it!

How to toggle with fade effect in jQuery?

Sometimes you need to toggle with fade in and fade out effects in jQuery. Toggle allows you to perform click and revert that click, or you can assign different functions to every click like this:

$('p').toggle(function(){
        alert("First click");
},function(){
       alert("Second Click");
},function(){
        alert("Third click");
});

In the above code we are using <p> tag as selector and if we click for the first time, it'll alert "First click" and if we click it for the second click, it'll alert "Second click" and so on.

fadeOut() will hide the content by fading it out and fadeIn() will show the hidden content. We are gonna use these effects to toggle content with fade effect.

$(':button').toggle(function(){
        $('img').fadeOut("slow");
},function(){
        $('img').fadeIn("slow");
});


The above code will hide and show images in your page when you clicked that button($(':button') ), with fade effect. Thats It!

Monday, 26 November 2012

How to install memcached on xampp - win 7

First download Win32 binary version of memcached here. Extract in any of ur folder outside xampp. I installed in c:/memcached/memcached.exe.

Then Go to your php.ini file usually located in C:/xampp/php/php.ini and find this line:

;extension=php_memcache.dll

then uncomment this line like this:

extension=php_memcache.dll

If you can't find this line add it at the end of the php.ini file:
Then add the following lines beneath this line:
[Memcache]  
memcache.allow_failover = 1  
memcache.max_failover_attempts=20  
memcache.chunk_size =8192  
memcache.default_port = 11211
 
Then download the memcached extension from here. For me php_memcache-5.4-vc9-x86 it works.
 Because I installed latest version of xampp. If the version id not right then it won't work. I've been searched for the correct version for whole day and finally found mine. 
 
Then extract that package in side c:/xampp/php/ext . Now restart ur Apache & MySql.
 
Then goto ur memcahed folder using command prompt and type like this:
c:\memcached\memcached.exe -d install  
If it say already installed or didn't show any errors then its been installed. Then start memcached using this command:
c:\memcached\memcached.exe -d start
 
Now create any test php file and test with memcache class like code given below:
 
<?php  
$memcache = new Memcache;  
$memcache->connect('localhost', 11211) or die ("Could not connect");  
  
$version = $memcache->getVersion();  
echo "Server's version: ".$version."<br/>\n";  
  
$tmp_object = new stdClass;  
$tmp_object->str_attr = 'test'; 
$tmp_object->int_attr = 123; 
 
$memcache->set('key', $tmp_object, false, 10) or  
die ("Failed to save data at the server"); 
echo "Store data in the cache (data will expire in 10 seconds) 
<br/>\n"; 
 
$get_result = $memcache->get('key');  
echo "Data from the cache:<br/>\n";  
  
var_dump($get_result);  
?> 

Thats It!

 
 

Friday, 23 November 2012

Why $smarty->is_cached() emits fatal error in smarty 3?

When we use the cache function is_cached() in smarty version 3 it'll emit fatal error as shown below:

Fatal error: Uncaught exception 'SmartyException' with message 'unknown method 'is_cached''

I've been searched all over the internet and couldn't find out the solution why it shows this error in latest version alone. But in documentation it is not deprecated. Then what the hell is going on with smarty 3.

Finally I found out that they changed the syntax of the function is_cached() in latest version.
According to latest version we have to declare it as isCached()

if(!$smarty->isCached("post.tpl",$postid)){
 $smarty->assign('image_url',$img_path);

$smarty->display('post.tpl',$postid);

We have to give cache id($post_id) for the function isCached() to make it work.Thats It!! I hope it works for u!!

Wednesday, 21 November 2012

How to strip Specific tag from HTML using smarty?

Usually in PHP and smarty there is a function called strip_tags to strip all the tags from HTML. But in if you want to strip <img> tag alone from the HTML or any other tag from HTML content we have to use some regular expressions.

If $content is the smarty variable which holds the HTML content, then use the below regex to parse it and strip <img> tag:

{$content | regex_replace:"/(<img>|<img [^>]*>|<\\/>)/":""}

We can use this to strip any html tags. If you wanna strip <p> tag:


{$content | regex_replace:"/(<p>|<p[^>]*>|<\\/p>)/":""}

This will replace <p>, </p> and all <p many attributes> strings with an empty string.

Thats It!!

Monday, 19 November 2012

How to use print_r() in smarty?

We use print_r() in php to print the arrays recursively. If you're using smarty templating engine we can't use the same to print the arrays recursively. We have to assign the array value in a smarty variable in the corresponding php like this:

$smarty->assign('contacts', array('fax' => '555-222-9876', 'cell' => '555-111-1234'));
$smarty->display('index.tpl');

Then open index.tpl and use the variable contacts like this:
{$contacts|@debug_print_var}

Thats it! it'll print the arrays recursively same as print_r() in PHP !!

Friday, 16 November 2012

How to get specific inline styles from Javascript?

At times we need to get specific inline styles from an HTML element. We can use jQuery to get that easily by specifying like $('#id').css('marginLeft');

But it will return the value of the margin-left inline style only in pixels(px), even if u specified in percentage(%) originally. To overcome that I've come across a solution using javascript using
document.getElementById('myDiv').style.cssText;
 
Code:
 
<script type="text/javascript">
function showStyles() {
    var s = document.getElementById('myDiv').style.cssText;
    var c = s.split(";");
    for ( var i = 0; i < c.length; i++ ) {
        var p = c[i].split(":");
        alert( p[0] + " is " + p[1] );
    }
}
</script> 

<div id="myDiv" style="height: 200px; width: 150px; margin-left: -10%;">
</div>
 
The above script will alert all the inline styles one by one exactly specified. If we
Want margin-left alone then use c[3] to output that. p[0] and p[1] specifies style 
attribute and value for the same.

Saturday, 3 November 2012

how to create mobile version of wordpress website?

There are lot of ways to do this. But this is simplest of all but not simpler than responsive site. This method is used to redirect mobile users to another sub-domain. So that you can reduce the load of the server from the same domain. Here I used another sub-domain for mobile version.

First you have to add redirect function to your sub-domain (http://m.example.com). So open the functions.php from your theme folder. Add the redirect function as given below:


function check_is_mobile(){
$cur_url = esc_url("http://".$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$mob_url= 'http://m.example.com/';
    if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android'))
            {
                $ex = explode("/",$cur_url);
                $postt_id= $ex[4];
                if(!empty($postt_id)){
                wp_redirect($mob_url.'post.php?id='.$postt_id);
                exit;
                }
                else{
                wp_redirect($mob_url);
                exit;
                }
            }
    }

add_action('wp_head','check_is_mobile',1);

 Then create an index.php file in your sub-domain folder and include the wp-blog-header.php. Then display list of post with the below code.
<?php require($_SERVER["DOCUMENT_ROOT"].'/blog/wp-blog-header.php');?>
  <div id="content">
<?php
     $args = array( 'numberposts' => 10, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
    $postslist = get_posts($args);
   
    foreach ($postslist as $post) : setup_postdata($post); ?>

    <?php add_filter('excerpt_more', 'new_excerpt_more');?>
       <div class="inner_box">        
           <p class="art_head"><a href="<?php echo $_SERVER["REQUEST_URI"]; the_ID(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></p>
           <div class="description">
           <?php the_excerpt();?>
           </div>
      </div>
      <?php endforeach; ?>
    </div>

 <?php
function new_excerpt_more( $more ) {
    return '[.....]';
}
?>


 

How to extract image name from the image url in php?

Sometimes we need to extract image name from the url of the image. For that use the below preg_match script:

<?php
if (preg_match('".*?/?([^/]+?(\.gif|\.png|\.jpg))"', $url, $regs)) {
    echo $image = $regs[1];
} else {
    $image = "";
}

?>
$url is the url of the image and $regs[1] gives the name of the image.Thats it!

Friday, 12 October 2012

How to use more than one navigation in wordpress?

In the backend of wordpress, Goto Appearance->Menus and add your custom menus for primary navigation and save it.

This is only for primary navigaton. Then how to create another navigation? Its pretty simple!. Click the '+' sign tab near the primary navigation on top. Then in the Menu Name enter the new name of the navigation in the text box and click Create  Menu.

Voila! New navigation is created. Now you can add your custom menus to that navigation. But in the front end it shows only primary navigation.
Where is the navigation which I created now ? Don't freak out! We have to call the navigation in our theme file at the place we are displaying..




Open your wordpress wp-content\themes\header.php and find the php function wp_nav_menu();. This is where your navigation displays in your site.

Now you need to display another navigation in your site. So just copy that navigation code(wp_nav_menu()--totally) and paste where You need another navigation. Then go to your admin backend of Appearance->Menus again and inspect Theme locations select box in your firebug or whatever.Clearly shown in image!!

You'll find the navigation created by us in the option like this
<option value="5">secondary navigation</option>

Note that value of our navigation and goto code where we left off. Now paste that value inside that wp_nav_menu() function with 'menu' as a key like this:
<?php wp_nav_menu( array( 'theme_location' => 'primary','menu' => '5' ) ); ?>
Here 5 is the value we are passing to display that navigation.

That It! Save the file and check the site.


Thursday, 4 October 2012

How to add review star ratings to google search results for your post?

This question was asked millions of times already, so I decided to put up an article and answer this once and for all.
 There are several ways to include ratings in reviews.The most common way is to include the rating written out as a number directly in the HTML, like this microformats example:

Rating: <span class="rating">4.5</span>

Also you can refer this link by Google which gives detailed information
on this.
But I'll show you the easiest way to achieve this. Just include the below
code anywhere inside your post or page to display rating for review.

<div>
   <span itemscope="itemscope" itemtype="http://data-vocabulary.org/Review">
   <span itemprop="itemreviewed">How to Use Ajax in Magento?</span>
   Rating: <span itemprop="rating">5</span> out of 5
   <span itemprop="reviewer">Vignesh M</span></span>
</div>

Leave the first <span> as it is. In the second <span> tag, You'll find
<span itemprop="itemreviewed">How to Use Ajax in Magento?</span>

It is used to say what we are reviewing or name of the post or product.
In the third line(Which is really important for displaying rating star),

 Rating: <span itemprop="rating">5</span> out of 5

Change the 5 inside the <span itemprop="rating"> to corresponding rating of
the review. Then in the next line you'll find,

<span itemprop="reviewer">Vignesh M</span></span>

It is essential to display ratings by specifying the name of the reviewer.
Then save the post and test the link with Google's Structured Data Testing Tool

Thats It!!

Friday, 28 September 2012

How to add Home link to wp_nav_menu() in Wordpress ?


If you want add “Home” link to your wordpress wp_nav_menu() function then you have to add following code inside your themes function.php file.
add_filter( 'wp_nav_menu_items', 'add_home_link', 10, 2 );
function add_home_link($items, $args) {
  
        if (is_front_page())
            $class = 'class="current_page_item"';
        else
            $class = '';
  
        $homeMenuItem =
                '<li ' . $class . '>' .
                $args->before .
                '<a href="' . home_url( '/' ) . '" title="Home">' .
                $args->link_before . 'Home' . $args->link_after .
                '</a>' .
                $args->after .
                '</li>';
  
        $items = $homeMenuItem . $items;
  
    return $items;
}
Then call the navigation menu in header.php like this:
<?php
if(function_exists('wp_nav_menu')):
wp_nav_menu(
array(
'menu' =>'primary_nav',
'container'=>'',
'depth' => 1,
'menu_id' => 'menu' )
);
else:
?>
<ul id="menu">
<li><a href="<?php bloginfo('url'); ?>" title="Home">Home</
a></li>
<?php wp_list_pages('title_li=&depth=1'); ?>
</ul>
<?php
endif;
?>

Wednesday, 26 September 2012

How to create a new page template in Wordpress?

In wordpress usually there is no option to select page template after a new installation. It will be usually located in the Edit page section of wordpress backend. Right side of this page you will find Page attributes with Parent and Order section. Once you created a new page template there will be another option called Template(Drop down).

Navigate to themes your folder which looks like this wp-content\themes\urtheme.
create a new php file or copy the existing page.php file in the same folder with your new template name. Then open that file and place the below code at the top of the page.
<?php
/*
Template Name: Home
*/


Home is the new template you created. Just go the Edit page of backend and you'll find template under Page attributes. There you can select your template for the page. That It! Then you can modify the new template you created as you wish.