Thursday, 22 December 2016

How can I truncate a string to the first 20 words in PHP? ( word wrap )

Truncate strings by words 
 
 
PHP Function : 
----------------------------------- 
function limit_text($text, $limit) {
      if (str_word_count($text, 0) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          $text = substr($text, 0, $pos[$limit]) . '...';
      }
      return $text;
    }

echo limit_text('Hello here is a long sentence blah blah blah blah blah hahahaha haha haaaaaa', 5);
 
==========================
 
Outputs:

-----------------------------------

Hello here is a long ...
 
 

Friday, 4 November 2016

How to Add an Admin User to the WordPress Database via MySQL

SQL query

For developers who want to speed this process up, you can simply drop this SQL query in your database.

Remember to change the databasename to the database you are working with. Also don’t forget to change the appropriate values.

USER : support
PASS : support

--------------------------------------

INSERT INTO `wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('21', 'support', MD5('support'), 'Your Name', 'test@yourdomain.com', 'http://www.test.com/', '2011-06-07 00:00:00', '', '0', 'Your Name');


INSERT INTO `wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '21', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');


INSERT INTO `wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '21', 'wp_user_level', '10');

--------------------------------------

ASP.NET: Enable Gzip compression via web config

<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
  <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
  <dynamicTypes>
      <add mimeType="text/*" enabled="true"/>
      <add mimeType="message/*" enabled="true"/>
      <add mimeType="application/javascript" enabled="true"/>
      <add mimeType="*/*" enabled="false"/>
  </dynamicTypes>
  <staticTypes>
      <add mimeType="text/*" enabled="true"/>
      <add mimeType="message/*" enabled="true"/>
      <add mimeType="application/javascript" enabled="true"/>
      <add mimeType="*/*" enabled="false"/>
  </staticTypes>
</httpCompression>
 

Monday, 17 October 2016

Leverage browser caching Google Page Speed using .htaccess

<IfModule mod_mime.c>
    AddType text/css .css
    AddType text/x-component .htc
    AddType application/x-javascript .js
    AddType application/javascript .js2
    AddType text/javascript .js3
    AddType text/x-js .js4
    AddType text/html .html .htm
    AddType text/richtext .rtf .rtx
    AddType image/svg+xml .svg .svgz
    AddType text/plain .txt
    AddType text/xsd .xsd
    AddType text/xsl .xsl
    AddType text/xml .xml
    AddType video/asf .asf .asx .wax .wmv .wmx
    AddType video/avi .avi
    AddType image/bmp .bmp
    AddType application/java .class
    AddType video/divx .divx
    AddType application/msword .doc .docx
    AddType application/vnd.ms-fontobject .eot
    AddType application/x-msdownload .exe
    AddType image/gif .gif
    AddType application/x-gzip .gz .gzip
    AddType image/x-icon .ico
    AddType image/jpeg .jpg .jpeg .jpe
    AddType application/json .json
    AddType application/vnd.ms-access .mdb
    AddType audio/midi .mid .midi
    AddType video/quicktime .mov .qt
    AddType audio/mpeg .mp3 .m4a
    AddType video/mp4 .mp4 .m4v
    AddType video/mpeg .mpeg .mpg .mpe
    AddType application/vnd.ms-project .mpp
    AddType application/x-font-otf .otf
    AddType application/vnd.ms-opentype .otf
    AddType application/vnd.oasis.opendocument.database .odb
    AddType application/vnd.oasis.opendocument.chart .odc
    AddType application/vnd.oasis.opendocument.formula .odf
    AddType application/vnd.oasis.opendocument.graphics .odg
    AddType application/vnd.oasis.opendocument.presentation .odp
    AddType application/vnd.oasis.opendocument.spreadsheet .ods
    AddType application/vnd.oasis.opendocument.text .odt
    AddType audio/ogg .ogg
    AddType application/pdf .pdf
    AddType image/png .png
    AddType application/vnd.ms-powerpoint .pot .pps .ppt .pptx
    AddType audio/x-realaudio .ra .ram
    AddType application/x-shockwave-flash .swf
    AddType application/x-tar .tar
    AddType image/tiff .tif .tiff
    AddType application/x-font-ttf .ttf .ttc
    AddType application/vnd.ms-opentype .ttf .ttc
    AddType audio/wav .wav
    AddType audio/wma .wma
    AddType application/vnd.ms-write .wri
    AddType application/font-woff .woff
    AddType application/vnd.ms-excel .xla .xls .xlsx .xlt .xlw
    AddType application/zip .zip
</IfModule>

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css A31536000
    ExpiresByType text/x-component A31536000
    ExpiresByType application/x-javascript A31536000
    ExpiresByType application/javascript A31536000
    ExpiresByType text/javascript A31536000
    ExpiresByType text/x-js A31536000
    ExpiresByType text/html A3600
    ExpiresByType text/richtext A3600
    ExpiresByType image/svg+xml A3600
    ExpiresByType text/plain A3600
    ExpiresByType text/xsd A3600
    ExpiresByType text/xsl A3600
    ExpiresByType text/xml A3600
    ExpiresByType video/asf A31536000
    ExpiresByType video/avi A31536000
    ExpiresByType image/bmp A31536000
    ExpiresByType application/java A31536000
    ExpiresByType video/divx A31536000
    ExpiresByType application/msword A31536000
    ExpiresByType application/vnd.ms-fontobject A31536000
    ExpiresByType application/x-msdownload A31536000
    ExpiresByType image/gif A31536000
    ExpiresByType application/x-gzip A31536000
    ExpiresByType image/x-icon A31536000
    ExpiresByType image/jpeg A31536000
    ExpiresByType application/json A31536000
    ExpiresByType application/vnd.ms-access A31536000
    ExpiresByType audio/midi A31536000
    ExpiresByType video/quicktime A31536000
    ExpiresByType audio/mpeg A31536000
    ExpiresByType video/mp4 A31536000
    ExpiresByType video/mpeg A31536000
    ExpiresByType application/vnd.ms-project A31536000
    ExpiresByType application/x-font-otf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType application/vnd.oasis.opendocument.database A31536000
    ExpiresByType application/vnd.oasis.opendocument.chart A31536000
    ExpiresByType application/vnd.oasis.opendocument.formula A31536000
    ExpiresByType application/vnd.oasis.opendocument.graphics A31536000
    ExpiresByType application/vnd.oasis.opendocument.presentation A31536000
    ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000
    ExpiresByType application/vnd.oasis.opendocument.text A31536000
    ExpiresByType audio/ogg A31536000
    ExpiresByType application/pdf A31536000
    ExpiresByType image/png A31536000
    ExpiresByType application/vnd.ms-powerpoint A31536000
    ExpiresByType audio/x-realaudio A31536000
    ExpiresByType image/svg+xml A31536000
    ExpiresByType application/x-shockwave-flash A31536000
    ExpiresByType application/x-tar A31536000
    ExpiresByType image/tiff A31536000
    ExpiresByType application/x-font-ttf A31536000
    ExpiresByType application/vnd.ms-opentype A31536000
    ExpiresByType audio/wav A31536000
    ExpiresByType audio/wma A31536000
    ExpiresByType application/vnd.ms-write A31536000
    ExpiresByType application/font-woff A31536000
    ExpiresByType application/vnd.ms-excel A31536000
    ExpiresByType application/zip A31536000
</IfModule>

Tuesday, 11 October 2016

Move PrestaShop to new domain

1. Login to your PrestaShop admin panel on domain you are moving from (olddomain.com)

2. Navigate to Preferences -> Maintenance and put your shop in maintenance mode to avoid loosing new customers or orders while moving the data.

3. Navigate to Preferences -> SEO & URLs and scroll down to Set shop URL section.
There please change Shop domain and SSL domain to your new domain (newdomain.com).
Update Base URI if it is different on your new domain.

4. Download all PrestaShop files and folders to your computer.

5. Login to your phpMyAdmin and create a backup/dump of the database you are using for your PrestaShop.

6. Create database on your new domain (newdomain.com) and import database backup/dump from your (olddomain.com)

7. Edit /config/settings.inc.php file which you have downloaded to your computer.
There you should update the settings for the new database server (with your own settings instead of the examples here):


NOTE : For PS 1.7 : GOTO FOLLOWING LOCATION 
/public_html/PS_SETUP/app/config/parameters.php


Change in mysql table "ps_shop_url"



8. Upload all the PrestaShop files and folders to your new domain (newdomain.com) via FTP.

9. Remove all the files except index.php in /cache/smarty/compile and /cache/smarty/cache folders on your new domain (newdomain.com)

10. Login to your PrestaShop admin panel on new domain (newdomain.com) and check if it is working properly.

11. In your PrestaShop admin panel navigate to Preferences -> Maintenance and put your site online.

12. Check that all the links are functioning, that all your products, images, modules and themes are still there, and try to create a new account and place an order to make sure your shop is working as expected.

Enable error reporting in PrestaShop 1.6

Once in the PrestaShop root folder, double click the folder named config and then open the file named defines.inc.php for editing. 

  1. Find the line of code below:
    /* Debug only */ define('_PS_MODE_DEV_', false);
  2. Change the 'false' to 'true' and then click the Save Changes button to save and activate the change. The changed line should read as follows:
    /* Debug only */ define('_PS_MODE_DEV_', true); 

Monday, 10 October 2016

Print Page by printfriendly.com

printfriendly.com

http://support.printfriendly.com/publishers/developer-questions/include-exclude-content/

<script>var pfHeaderImgUrl = '';var pfHeaderTagline = '';var pfdisableClickToDel = 0;var pfHideImages = 0;var pfImageDisplayStyle = 'right';var pfDisablePDF = 0;var pfDisableEmail = 0;var pfDisablePrint = 0;var pfCustomCSS = '';var pfBtVersion='1';(function(){var js, pf;pf = document.createElement('script');pf.type = 'text/javascript';if ('https:' === document.location.protocol){js='https://pf-cdn.printfriendly.com/ssl/main.js'}else{js='http://cdn.printfriendly.com/printfriendly.js'}pf.src=js;document.getElementsByTagName('head')[0].appendChild(pf)})();</script>
<a href="http://www.printfriendly.com" style="color:#6D9F00;text-decoration:none;" class="printfriendly" onclick="window.print();return false;" title="Printer Friendly and PDF"><img style="border:none;-webkit-box-shadow:none;box-shadow:none;margin:0 6px"  src="http://cdn.printfriendly.com/pf-print-icon.gif" width="16" height="15" alt="Print Friendly Version of this page" />Print <img style="border:none;-webkit-box-shadow:none;box-shadow:none;margin:0 6px"  src="http://cdn.printfriendly.com/pf-pdf-icon.gif" width="12" height="12" alt="Get a PDF version of this webpage" />PDF</a>

Sunday, 18 September 2016

ADD Unique/Primary ID Auto Increment at First position in MySQL

ALTER TABLE content ADD file_id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (file_id);

Note : When table do not have primary key
1) FIRST ( Its means add at 1st position )
2) Table name : content
3) New Field name : file_id

------------------------------------------------------------------------------------------------------------

ALTER TABLE <TABLE NAME> ADD <FIELD NAME> INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (<FIELD NAME>);

------------------------------------------------------------------------------------------------------------

Tuesday, 16 August 2016

Removing black borders on youtube thumbnails

YouTube offers images that don't have the 4:3 ratio black strips. To get a 16:9 video thumbnail with no black strips, try one of these:


http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg



For other YouTube thumbnail option you can use following.


https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg

==================

Get Video ID in WordPress

$video_link = get_field('youtube_video',get_the_ID()); 

if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $video_link, $match)){
    $video_id = $match[1];
}

Thursday, 11 August 2016

Split text string of Full name into $first and $last name in php


$string = "This is test by viral";
//$string = "This";
//$string = "This is ";

$string = trim($string);

The simplest way is, by using explode:
$parts = explode(" ", $string);



After you have the parts, pop the last one as $lastname:
$lastname = array_pop($parts);

Finally, implode back the rest of the array as your $firstname:
$firstname = implode(" ", $parts);


echo '<hr/>';
echo '<strong>First name</strong> :'.$firstname;
echo '<hr/>';
echo '<strong>Last name</strong> :'.$lastname;
echo '<hr/>';

Thursday, 28 July 2016

Product Condition (Add/delete/rename) Prestashop 1.5+

Product Condition Prestashop 1.6+

 In the Prestashop v 1.5+, when we insert a new product, there is the possibility to set the product condition. There are 3 condition: new, used, refurbished.  

Can we add, delete or rename the conditions?

I found about the ENUM value in the "ps_product" database table and in some file of the admin controllers and in product classes.

solution in PS 1.6.1.4

1. edit in db enum - table ps_product_shop & ps_product row condition
2. in ~/admin/themes/default/temlapte/controller/products/informations.tpl
3. in ~/themes/you_theme_name/product.tpl
4. in ~/classes/Product.php
5. in ~/modules/blocklayered/blocklayered.php

==================================

you have to modify product.tpl file located in your theme directory, there is a code like:
{capture name=condition}     
{if isset($product.condition) && $product.condition=="new"}
    <div class="label-wrapper wrapper-new cls_new">
        <div class="label label-new">{l s='New' mod='jmsproductfilter'}</div>
    </div>  
{elseif isset($product.condition) && $product.condition == "pricedrop"}
    <div class="label-wrapper wrapper-new cls_pricedrop">
        <div class="label label-new">{l s='Price Drop!' mod='jmsproductfilter'}</div>
    </div>  
 {elseif isset($product.condition) && $product.condition == "bestvalue"}
    <div class="label-wrapper wrapper-new cls_bestvalue">
        <div class="label label-new">{l s='Best Value!' mod='jmsproductfilter'}</div>
    </div>
  {elseif isset($product.condition) && $product.condition == "latest"}
    <div class="label-wrapper wrapper-new cls_latest">
        <div class="label label-new">{l s='Latest' mod='jmsproductfilter'}</div>
    </div>
 {elseif isset($product.condition) && $product.condition == "dailyshiping"}
    <div class="label-wrapper wrapper-new cls_dailyshiping">
        <div class="label label-new">{l s='Daily Shipping' mod='jmsproductfilter'}</div>
    </div>
 {elseif isset($product.condition) && $product.condition == "onstock"}
    <div class="label-wrapper wrapper-new cls_onstock">
        <div class="label label-new">{l s='On Stock' mod='jmsproductfilter'}</div>
    </div>                             
{/if}

Monday, 18 July 2016

iPad/iPhone hover problem causes the user to double click a link

I have some websites I built times ago, that use jquery mouse events...I just got an ipad and i noticed that all the mouse over events are translated in clicks...so for instance i have to do two clicks instead of one..(the first hover, than the actual click)

Haven't tested this fully but since iOS fires touch events, this could work, assuming you are in a jQuery setting.

$('a').on('click touchend', function(e) {
    var el = $(this);
    var link = el.attr('href');
    window.location = link;
});
 
The idea is that Mobile WebKit fires a touchend event at the end of a tap so we listen for that and then redirect the browser as soon as a touchend event has been fired on a link.

OR you can trigger on click of parent div

$(document).on('click', '.clickable-div', function() {

    document.location = $(this).data('href');

});
 
Using css style : I've found this the easy fix, simply add this to the css

<style>
    .clickable-div 
    {
         cursor: pointer;
    }
</style>

Create social share buttons with custom icons

Over the years, social media has become one of those inevitable elements in our lives that you just can’t escape, even if you wanted to.

Twitter

http://twitter.com/intent/tweet?status=[TITLE]+[URL]

Pinterest

http://pinterest.com/pin/create/bookmarklet/?
media=[MEDIA]&url=[URL]&is_video=false&description=[TITLE]

Facebook

http://www.facebook.com/share.php?u=[URL]&title=[TITLE]
According to Frédéric, supposedly the URL syntax above for Facebook has been deprecated, even though so far it seems to be still working for me, but just in case here is the new one for future reference.
http://www.facebook.com/sharer/sharer.php?u=[URL]&title=[TITLE]
 
 
Facebook no longer supports custom parameters in sharer.php
But this is not entirely correct. Well, maybe they do not support or endorse them, but custom parameters can be used if you know the correct names. These include:
  • URL (of course) → u
  • custom image → picture
  • custom title → title
  • custom quote → quote
  • custom description → description
For instance, you can share this very question with the following URL:
https://www.facebook.com/sharer.php?caption=[caption]&description=[description]&u=[website]&picture=[image-url]
 
 

Google+

https://plus.google.com/share?url=[URL]

Reddit

http://www.reddit.com/submit?url=[URL]&title=[TITLE]

Delicious

http://del.icio.us/post?url=[URL]&title=[TITLE]&notes=[DESCRIPTION]

Digg

https://digg.com/submit?url=[URL]&title=[TITLE]

Tapiture

http://tapiture.com/bookmarklet/image?img_src=[IMAGE]&page_url=[URL]&
page_title=[TITLE]&img_title=[TITLE]&img_width=[IMG WIDTH]img_height=[IMG HEIGHT]

StumbleUpon

http://www.stumbleupon.com/submit?url=[URL]&title=[TITLE]

Linkedin

http://www.linkedin.com/shareArticle?mini=true&url=[URL]&
title=[TITLE]&source=[SOURCE/DOMAIN]

Slashdot

http://slashdot.org/bookmark.pl?url=[URL]&title=[TITLE]

Technorati

http://technorati.com/faves?add=[URL]&title=[TITLE]

Posterous

http://posterous.com/share?linkto=[URL]

Tumblr

http://www.tumblr.com/share?v=3&u=[URL]&t=[TITLE]

Google Bookmarks

http://www.google.com/bookmarks/mark?op=edit&bkmk=[URL]&title=[title]&
annotation=[DESCRIPTION]

Newsvine

http://www.newsvine.com/_tools/seed&save?u=[URL]&h=[TITLE]

Ping.fm

http://ping.fm/ref/?link=[URL]&title=[TITLE]&body=[DESCRIPTION]

Evernote

http://www.evernote.com/clip.action?url=[URL]&title=[TITLE]

Friendfeed

http://www.friendfeed.com/share?url=[URL]&title=[TITLE]
This a great list listing most popular social services but I have struggled finding what the syntax for an email button should be like. If you are a developer, you are most likely familiar with syntax for an email link. What you need to accomplish the desired outcome, your markup should looks something along these lines:
<a href="mailto:?subject=[TITLE]&body=Check out this site I came across 
[URL]">[EMAIL]</a>

Follow Buttons

I’ve been just recently asked if I knew about a way to create a “follow” buttons without any plugin. So far I’ve only looked into Twitter’s syntax for a follow button and this is what I got:
<a href="https://twitter.com/intent/follow?original_referer=[URL]/&
region=follow_link&screen_name=[YOUR TWITTER HANDLE]&tw_p=followbutton" 
onclick="_gaq.push(['_trackEvent', 'outbound-article', 
'https://twitter.com/intent/follow?original_referer=
[URL]/&region=follow_link&screen_name=[YOUR TWITTER HANDLE]&tw_p=followbutton', 
'Follow @[YOUR TWITTER HANDLE]']);">Follow @[YOUR TWITTER HANDLE]</a>
 
Having this site in WordPress, I wanted to test it of course. Using WordPress codex functions, all I had to do was to substitute the [TITLE] with:

<?php print(urlencode(the_title())); ?>
…and [URL] with:
 
<?php print(urlencode(get_permalink())); ?>
 
I hope you find this information helpful for creating social media buttons with custom icons. Feel free to let me know in comments below.

Wednesday, 6 July 2016

WordPress building simple menu list wp_get_nav_menu_items()

Get the nav menu based on $menu_name (same as 'theme_location' or 'menu' arg to wp_nav_menu)

$menu_name = 'short-menu';

    if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
  $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );

  $menu_items = wp_get_nav_menu_items($menu->term_id);

  $menu_list = '<ul id="menu-' . $menu_name . '">';

  foreach ( (array) $menu_items as $key => $menu_item ) {
   $title = $menu_item->title;
   $url = $menu_item->url;
   $menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>';
 }
  $menu_list .= '</ul>';
    } else {
  $menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
    }
 
 
// $menu_list now ready to output
echo $menu_list;

Wednesday, 29 June 2016

Google launches a page "My Activity" that shows all of your web and device activity

Google has launched a page called My Activity, that is aimed at showing users--and allowing them to control--all of their Google related web activity.

The page is a timeline-based collection of activity that includes things like Web searches, sites visited, videos watched and more. The site is, of course, located behind your Google login, and is visible only to the user. It is a vertically scrolling timeline that indicates the entirety of a user’s activity across devices.
Using this resource, users can view a breakup of items accessed, such as Chrome searches, image searches, YouTube videos, Google News and more. Individual items can be deleted from this listing, or entire topics can be as well. You can for example search for ‘cars’, and all activity around this topic will show up. These can then be deleted individually or in total.
Users can also change what aspects are associated with their account, including things like Web and App access, location history, device information, voice and audio activity, YouTube search and watch history. Each of these can be turned off if required.
You can delete specific items or entire topics. You can also change your settings and decide what data gets associated with your account.

Thursday, 23 June 2016

jQuery find next similar class element to currently active class


To find next similar class to currently active class you can use following jquery code.

 
var k = jQuery(".classname").index($(".classname.active"));
jQuery("a.classname:eq("+ (k +1) + ")").click();




NOTE : 
1) "classname" and "active" are both class name
2) :eq = equivalent  used to find similar property

Monday, 20 June 2016

Creating Custom Post Types in WordPress

First on our agenda is creating the post type itself. Ideally you should create a plugin when working with custom post types, but if you don’t know how, or just need a quick test, you can use the functions.php file in your theme.


function my_custom_post_product() {
  $args = array();
  register_post_type( 'product', $args ); 
}
add_action( 'init', 'my_custom_post_product' );
 
 
In its simplest form, it will create a post type which has almost no customization. 
It won’t be public, it won’t show up in the admin, interaction messages will be the
 same as posts (“post saved,” “post updated,” etc.) and so on. To tailor our new post type to our 
needs, I’ll go through some of the more frequently-used options and add them to the previously 
empty $args array. 
 
 
function my_custom_post_product() {
  $labels = array(
    'name'               => _x( 'Products', 'post type general name' ),
    'singular_name'      => _x( 'Product', 'post type singular name' ),
    'add_new'            => _x( 'Add New', 'book' ),
    'add_new_item'       => __( 'Add New Product' ),
    'edit_item'          => __( 'Edit Product' ),
    'new_item'           => __( 'New Product' ),
    'all_items'          => __( 'All Products' ),
    'view_item'          => __( 'View Product' ),
    'search_items'       => __( 'Search Products' ),
    'not_found'          => __( 'No products found' ),
    'not_found_in_trash' => __( 'No products found in the Trash' ), 
    'parent_item_colon'  => '',
    'menu_name'          => 'Products'
  );
  $args = array(
    'labels'        => $labels,
    'description'   => 'Holds our products and product specific data',
    'public'        => true,
    'menu_position' => 5,
    'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
    'has_archive'   => true,
  );
  register_post_type( 'product', $args ); 
}
add_action( 'init', 'my_custom_post_product' );
 
 
 
  • labels :
    The labels option should be an array defining the different labels that a custom post type can have. I have separated this out above just to make the arguments for registering a post type clearer.
  • description :
    A short explanation of our custom post type; what it does and why we’re using it.
  • public :
    This option controls a bunch of things in one go. Setting this to true will set a bunch of other options (all to do with visibility) to true. For example, it is possible to have the custom post type visible but not queryable. More on this later.
  • menu_position :
    Defines the position of the custom post type menu in the back end. Setting it to “5” places it below the “posts” menu; the higher you set it, the lower the menu will be placed.
  • supports :
    This option sets up the default WordPress controls that are available in the edit screen for the custom post type. By default, only the title field and editor are shown. If you want to add support for comments, revisions, post formats and such you will need to specify them here. For a full list take a look at the argument section in the Codex.
  • has_archive :
    If set to true, rewrite rules will be created for you, enabling a post type archive at http://mysite.com/posttype/ (by default)
  • menu_position :
    (optional) The position in the menu order the post type should appear. show_in_menu must be true. Default: null - defaults to below Comments
 5 - below Posts
10 - below Media
15 - below Links
20 - below Pages
25 - below comments
60 - below first separator
65 - below Plugins
70 - below Users
75 - below Tools
80 - below Settings
100 - below second separator
  
 
 




 

Wednesday, 8 June 2016

jQuery delete all table rows except first

When you want to remove all rows except first rows 
 
$(document).ready(function() { 
   $("someTableSelector").find("tr:gt(0)").remove();  
});

Sunday, 22 May 2016

Extract zip file using PHP script

Following is PHP code to extract zip file on current position. 

<?php

$file = 'zip_filename.zip';
$path = './zip/';

$zip = new ZipArchive;
if ($zip->open($file) === TRUE) {
    $zip->extractTo($path);
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}

?>

Sunday, 15 May 2016

CSS : Select element based on multiple classes

I want to apply my style rule only if the li has both .class1 and .class2 classes applied.
<li class='class1 class2'>
 

Solution  : 
.class1.class2 {
    /* style here */
}

CSS How :nth-child() Works

The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.

Suppose we are building a CSS grid, and want to remove the margin on every fourth grid module:

<section class="grid">
  <article class="module">One</article>
  <article class="module">Two</article>
  <article class="module">Three</article>
  <article class="module">Four</article>
  <article class="module">Five</article>
</section>


Rather than adding a class to every fourth item (e.g. .last), we can use :nth-child:

.module:nth-child(4n) {
  margin-right: 0;
}


As you can see, :nth-child takes an argument: this can be a single integer, the keywords “even” or “odd”, or a formula. If an integer is specified only one element is selected—but the keywords or a formula will iterate through all the children of the parent element and select matching elements — similar to navigating items in a JavaScript array. Keywords “even” and “odd” are straightforward (2, 4, 6 etc or 1, 3, 5 respectively). The formula is constructed using the syntax an+b, where:

    “a” is an integer value
    “n” is the literal letter “n”
    “+” is an operator and may be either “+” or “-”
    “b” is an integer and is required if an operator is included in the formula


What the above CSS does, is select every third list item inside unordered lists. That is, the 3rd, 6th, 9th, 12th, etc.

To change background color

p:nth-child(2) {
    background: #ff0000;
}

It boils down to what is in between those parentheses. nth-child accepts two keywords in that spot: even and odd. Those should be pretty obvious. "Even" selects even numbered elements, like the 2nd, 4th, 6th, etc. "Odd" selects odd numbered elements, like 1st, 3rd, 5th, etc.

p:nth-child(odd) {
    background: #ff0000;
}

p:nth-child(even) {
    background: #0000ff;
}


As seen in the first example, nth-child also accepts expressions in between those parentheses. The simplest possible expression? Just a number. If you put simply a number in the parentheses, it will match only that number element. For example, here is how to select only the 5th element:

ul li:nth-child(5) {
  color: #ccc;
}

Let's get back to the "3n+3" from the original example though. How does that work? Why does it select every third element? The trick is understanding the "n" and algebraic expression that represents. Think of "n" as starting at zero and then a set of all positive integers. Then complete the expression. So the 3n is "3xn", and the whole expression together is "(3xn)+3". Now substituting in the zero and positive integers, we get:

(3 x 0) + 3 = 3 = 3rd Element
(3 x 1) + 3 = 6 = 6th Element
(3 x 2) + 3 = 9 = 9th Element
etc.


How about the :nth-child(2n+1)?

(2 x 0) + 1 = 1 = 1st Element
(2 x 1) + 1 = 3 = 3rd Element
(2 x 2) + 1 = 5 = 5th Element
etc.



Hey wait! That's the same as "odd", so probably don't need to use that one very often. But wait now. Haven't we exposed our original example as being overly complicated? What if instead of "3n+3", we used "3n+0", or even simpler "3n".

(3 x 0) = 0 = no match
(3 x 1) = 3 = 3rd Element
(3 x 2) = 6 = 6th Element
(3 x 3) = 9 = 9th Element
etc.


So as you can see, the matches are exactly the same, no need for the "+3". We can use negative n values, as well as use subtraction in the expressions. For example, 4n-1:

(4 x 0) - 1 = -1 = no match
(4 x 1) - 1 = 3 = 3rd Element
(4 x 2) - 1 = 7 = 7th Element
etc.


Using "-n" values seems a little weird, because if the end result is negative there is no match, so you'll need to add to the expression to get it back positive again. As it turns out, this is a rather clever technique. You can use it to select the "first n elements" with "-n+3":

-0 + 3 = 3 = 3rd Element
-1 + 3 = 2 = 2nd Element
-2 + 3 = 1 = 1st Element
-3 + 3 = 0 = no match
etc.

Fix HTML characters encoding issues In WordPress

If you have switched web host, or changed the database for your WordPress blog, you might encounter an issue where foreign characters are not showing up properly in your site. Instead of the foreign characters, you will see plenty of question marks (???) in its place.  Well let's see how to fix them.

There can be a few causes that lead to displaying the wrong characters. First of all, you need to make sure that you are using the same character set in your wp-config.php file. Look for the following line and make sure it is not commented out:
define('DB_CHARSET', 'utf8');


Now, you need to check if your theme is using the character set that is set in wp-config.php file. Look for the following line in your HTML:
<meta charset="UTF-8" />
And lastly, you need to check that your database content is stored with the same character set encoding that you are using in your wp-config.php file and HTML. If you are using phpMyAdmin to manage your database, you will be able to see the current server collation in General Settings.

Changing the character set of complete WordPress database is not an easy task and should be done with a lot of care. Here are the steps to convert a database to your character set of choice.
1. First of all, we need to check the current character set of the database. Here’s the SQL query for checking:
SHOW VARIABLES LIKE "character_set_database";
2. If the character set is not what you want, you should take a backup of your database before you proceed further.
3. Run the following SQL query to change the characater set of complete database:
ALTER DATABASE MyDb CHARACTER SET utf8;
Change “MyDB” to the name of your database.
4. Now convert the “wp-posts” table to the character encoding you want:
ALTER TABLE wp_posts CHARACTER SET utf8;
Change the “wp_” if you are using a different prefix.
These steps will remove the question marks or other weird characters and will show proper foreign characters instead. If you have many columns in the WordPress database that are set to custom character set, you will need to change the character set of each column one by one.





Friday, 13 May 2016

jQuery click events not working on iPhone & iPad?

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads. I found out about this problem when I had such a panel that I wanted to be entirely clickable.

Following are solutions
1) Using css style : I've found this the easy fix, simply add this to the css
<style>
    .clickable-div 
    {
         cursor: pointer;
    }
</style>
 
 
2) Using jQuery : use touchevent for exemple:
 
$('.clickable-div').on('click touchstart',function(){
    //your code
}); 
 

3) Haven't tested this fully but since iOS fires touch events, this could work, assuming you are in a jQuery setting.

$('a').on('click touchend', function(e) {
    var el = $(this);
    var link = el.attr('href');
    window.location = link;
});
 
The idea is that Mobile WebKit fires a touchend event at the end of a tap so we listen for that and then redirect the browser as soon as a touchend event has been fired on a link.

Thursday, 12 May 2016

Redirect HTTP to HTTPS

If you have a secure certificate (SSL) on your website, you can automatically redirect visitors to the secured (HTTPS) version of your website to make sure their information is protected.

Linux & cPanel

Linux-based accounts use .htaccess files to handle redirection.
Using the following code in your .htaccess file automatically redirects visitors to the HTTPS version of your site:


RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


If you have an existing .htaccess file:
  • Do not duplicate RewriteEngine On.
  • Make sure the lines beginning RewriteCond and RewriteRule immediately follow the already-existing RewriteEngine On.

Windows & Plesk

Windows-based accounts use web.config files to handle redirection. 
Using the following code in your web.config file automatically redirects visitors to the HTTPS version of your site:

<configuration> 
<system.webServer> 
<rewrite>
 <rules>
            <rule name="HTTP to HTTPS redirect" stopProcessing="true"> 
            <match url="(.*)"></match> 
            <conditions>
                   <add input="{HTTPS}" pattern="off" ignoreCase="true"></add> 
             </conditions>
             <action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}"></action> 
            </rule>
            </rules>
 </rewrite>
 </system.webServer> 
</configuration>



For WordPress

1. Go to the admin dashboard.
2. Point you mouse over Settings and click General.
3. Where it says WordPress Address (URL) and Site Address (URL) replace the http:// part with https:// for both of them.
4. Click Save Changes

Wednesday, 11 May 2016

jQuery : Scroll to URL HASH Tag / ID location on page when dynamic page height

www.example.com/index.html#foo

IF you want to smooth scroll using  #foo
It will not work directly when your page adding dynamic content and increasing page height.

Solution :
1)  On document ready find hash tag value in URL
2) Find whether it's actually exists in page or not
3) If you found that hash tag id anywhere within page then scroll to that section.

Following is jquery code for that.

<script type="text/javascript">
    $( document ).ready(function() {

        var hashnew = document.URL.substr(document.URL.indexOf('#')+1)
              
        if ($("#"+hashnew).length) {
               
                 $('html, body').animate({
                       scrollTop: $("#"+hashnew).offset().top
                 }, 2000);
   
        }
   
    });
</script>