Friday, February 24, 2017

Add tag and category to custom post type

Hi.
Here i share simple code for create tag and category for custom post type. Put this code in functions.php in your theme folder



//hook into the init action and call create_Category_nonhierarchical_taxonomy when it fires

add_action( 'init', 'create_Category_nonhierarchical_taxonomy', 0 );

function create_Category_nonhierarchical_taxonomy() {

// Labels part for the GUI

  $labels = array(
    'name' => _x( 'Categories', 'taxonomy general name' ),
    'singular_name' => _x( 'Category', 'taxonomy singular name' ),
    'search_items' =>  __( 'Search Category' ),
    'popular_items' => __( 'Popular Category' ),
    'all_items' => __( 'All Category' ),
    'parent_item' => null,
    'parent_item_colon' => null,
    'edit_item' => __( 'Edit Category' ),
    'update_item' => __( 'Update Category' ),
    'add_new_item' => __( 'Add New Category' ),
    'new_item_name' => __( 'New Category Name' ),
    'separate_items_with_commas' => __( 'Separate Category with commas' ),
    'add_or_remove_items' => __( 'Add or remove Category' ),
    'choose_from_most_used' => __( 'Choose from the most used Category' ),
    'menu_name' => __( 'Category' ),
  );

// Now register the non-hierarchical taxonomy like tag

  register_taxonomy('RCategory','resources',array(
    'hierarchical' => true,
    'labels' => $labels,
    'show_ui' => true,
    'show_admin_column' => true,
    'update_count_callback' => '_update_post_term_count',
    'query_var' => true,
    'rewrite' => array( 'slug' => 'rcategory' ),
  ));
  register_taxonomy(
            'resources_tag',
            'resources',
            array(
                'hierarchical'  => false,
                'label'         => __( 'Tags', CURRENT_THEME ),
                'singular_name' => __( 'Tag', CURRENT_THEME ),
                'rewrite'       => true,
                'query_var'     => true
            ) 
        );
}
//end code

Thursday, February 23, 2017

How to parse XML in PHP – simpleXML

Hello all,

Many websites on internet like to share their feed in XML format so that other website owner can show that feed on his/her website / blog. In PHP there is a function called simpleXML can simplify the process of reading the feeds into something useful for your web pages.

 If You have wordpress installed in your server you can also on Rss feed of your blog and share your news/ articles with other websites. this will increase your blog visibility and good for SEO also.

Here is sample xml file.
companydb.xml

<?xml version='1.0'?>
<companydb>
  <company>
        <name>Chirag</name>
        <city>Ahmedabad</city>
        <phone>121212</phone>
  </company>
    <company>
        <name>Parmar</name>
        <city>Mumbai</city>
        <phone>121212</phone>
  </company>
</companydb>
 With simpleXML, it’s as easy reading the XML file and then accessing it’s contents by an easy to read object. Suppose we have our XML file above saved as a file called comopanydb.xml with all the company details in the same folder as our php file, we can read the whole xml feed by following php function.

$companydb = simplexml_load_file('companydb.xml');
 
Now we have created file object, go next for accessing it’s content. 
like if you want to display the name of the all companies then use below
 code.
 
<?php
    $companydb = simplexml_load_file('companydb.xml');
    foreach ($companydb as $company) {
        echo $title=$company->name." - ".$company->city." - ".$company->phone."<br/>";
  } 
?>
 
Above is the quick example for parsing xaml data in php, you can store you 
data in xml file and access with this method.  
 

Wednesday, February 22, 2017

File size and extension validation before upload in javascript

It is a good idea to apply quick client side validation on file / image upload in javaScript, You can easily check file extension and size before file upload, So that user won’t be allow to upload garbage and large size of files. And this is good approach to maintain good server health to prevent garbage files.
 Full Code :

<div style="margin:0 auto; width:50% text-align:center">
<form id="form">
    <input type='file' id="file" />
    <br/>
   <span style="color:red"> Note: Please select only image file (eg: .png, .jpeg, .jpg, .gif etc)<br/> Max File size : 1MB allowed </span><br/>
    <img id="img" src="http://placehold.it/200x200" alt="No image uploaded" />
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function() {
$("#file").change(function () {
        if(fileExtValidate(this)) {
             if(fileSizeValidate(this)) {
                 showImg(this);
             }   
        }   
    });

// File extension validation, Add more extension you want to allow
var validExt = ".png, .gif, .jpeg, .jpg";
function fileExtValidate(fdata) {
 var filePath = fdata.value;
 var getFileExt = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
 var pos = validExt.indexOf(getFileExt);
 if(pos < 0) {
     alert("This file is not allowed, please upload valid file.");
     return false;
  } else {
      return true;
  }
}

// file size validation
// size in kb
var maxSize = '1024';
function fileSizeValidate(fdata) {
     if (fdata.files && fdata.files[0]) {
                var fsize = fdata.files[0].size/1024;
                if(fsize > maxSize) {
                     alert('Maximum file size exceed, This file size is: ' + fsize + "KB");
                     return false;
                } else {
                    return true;
                }
     }
 }

 // display img preview before upload.
function showImg(fdata) {
        if (fdata.files && fdata.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#img').attr('src', e.target.result);
            }

            reader.readAsDataURL(fdata.files[0]);
        }
    }
});
</script>

Friday, February 17, 2017

click on div and arrange its position as first

Hello. Here i want to saw code for arrange div.
Suppose there are 5 div. All are arranged. When u click on third div, it will come to first position.


<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

 <script type="text/javascript">

 $(document).ready(function(){
    $(".item-post").click(function() {
      $('.news-layout-1').prepend($(this));
  });

});

 
 </script>
 <style type="text/css">
  h1 { cursor: pointer }
 </style>
</head>
<body>
 <div class="news-layout-1">
   <div class="item-post"><h1 class="item-title">First One</h1></div>
   <div class="item-post"><h1 class="item-title">Second One</h1></div>
   <div class="item-post"><h1 class="item-title">Third One</h1></div>
   <div class="item-post"><h1 class="item-title">Fourth One</h1></div>
   <div class="item-post"><h1 class="item-title">Fifth One</h1></div>
 </div>
</body>
</html>

Which programming language has the highest craze in the industries?



1. SQL
It’s no surprise SQL (pronounced ‘sequel’) tops the job list since it can be found far and wide in various flavors. Database technologies such as MySQL, PostgreSQL and Microsoft SQL Server power big businesses, small businesses, hospitals, banks, universities. Indeed, just about every computer and person with access to technology eventually touches something SQL. For instance, all Android phones and iPhones have access to a SQL database called SQLite and many mobile apps developed Google, Skype and DropBox use it directly.

2. Java
The tech community recently celebrated the 20th anniversary of Java. It’s one of the most widely adopted programming languages, used by some 9 million developers and running on 7 billion devices worldwide. It’s also the programming language used to develop all native Android apps. Java’s popularity with developers is due to the fact that the language is grounded in readability and simplicity. Java has staying power since it has long-term compatibility, which makes sure older applications continue to work now into the future.

3. JavaScript
JavaScript – not to be confused with Java – is another one of the world’s most popular and powerful programming languages, and is used to spice up web pages by making them interactive. For example, JavaScript can be used to add effects to web pages, display pop-up messages or to create games with basic functionality. It’s also worth noting that JavaScript is the scripting language of the World Wide Web and is built right into all major web browsers including Internet Explorer, FireFox and Safari. Almost every website incorporates some element of JavaScript to add to the user experience, adding to the demand for JavaScript developers. In recent years JavaScript has also gained use as the foundation of Node.js, a server technology that among other things enables real-time communication.

4. C#
Dating from 2000, C# (pronounced C-sharp) is a relatively new programming language designed by Microsoft for a wide range of enterprise applications that run on the .NET Framework. An evolution of C and C++, the C# language is simple, modern, type safe and object oriented.

5. C++
C++ (pronounced C-plus-plus) is a general purpose object-oriented programming language based on the earlier ‘C’ language. Developed by Bjarne Stroustrup at Bell Labs, C++ was first released in 1983. Stroustrup keeps an extensive list of applications written in C++. The list includes Adobe and Microsoft applications, MongoDB databases, large portions of Mac OS/X and is the best language to learn for performance-critical applications such as “twitch” game development or audio/video processing.

6. Python
Python is a general purpose programming language that was named after the Monty Python (so you know it’s fun to work with)! Python is simple and incredibly readable since closely resembles the English language. It’s a great language for beginners, all the way up to seasoned professionals. Python recently bumped Java as the language of choice in introductory programming courses with eight of the top 10 computer science departments now using Python to teach coding, as well as 27 of the top 39 schools. Because of Python’s use in the educational realm, there are a lot of libraries created for Python related to mathematics, physics and natural processing. PBS, NASA and Reddit use Python for their websites.

7. PHP
Created by Danish-Canadian programmer Rasmus Lerdorf in 1994, PHP was never actually intended to be a new programming language. Instead, it was created to be a set of tools to help Rasmus maintain his Personal Home Page (PHP). Today, PHP (Hypertext Pre-Processor) is a scripting language, running on the server, which can be used to create web pages written in HTML. PHP tends to be a popular languages since its easy-to use by new programmers, but also offers tons of advanced features for more experienced programmers.

8. Ruby on Rails
Like Java or the C language, Ruby is a general purpose programming language, though it is best known for its use in web programming, and Rails serves as a framework for the Ruby Language. Ruby on Rails has many positive qualities including rapid development, you don’t need as much code, and there are a wide variety of 3rd party libraries available. It’s used from companies ranging from small start-ups to large enterprises and everything in-between. Hulu, Twitter, Github and Living Social are using Ruby on Rails for at least one of their web applications.

9. iOS/Swift
In 2014, Apple decided to invent their own programming language. The result was Swift – a new programming language for iOS and OS X developers to create their next killer app. Developers will find that many parts of Swift are familiar from their experience of developing in C++ and Objective-C. Companies including American Airlines, LinkedIn, and Duolingo have been quick to adopt Swift, and we’ll see this language on the rise in the coming years.


Wednesday, February 8, 2017

WordPress interview questions and answers for freshers

These WordPress Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of WordPress. In this post I have compiled a list of top frequently asked WordPress interview questions and answers for freshers, This list of WordPress interview questions and answers will be helpful for WordPress beginner who just started their career as WordPress developer, and surely help you during interview session.



Question: What is WordPress?


WordPress is a free and open source popular blogging tool and a content management system (CMS) based on PHP and MySQL.It is absolutely free of cost and you can use it to create any type of personal and commercial website.

Question: What are Developer Features in a WordPress?


For developers, WordPress Have lots of goodies packed under the hood that you can use to extend WordPress in whatever direction takes your fancy.
1. Theme System
2. Plugin System
3. Custom Content Types
4. The Latest Libraries
5. Application Framework

Question: Is a website on WordPress safe and secure?


Creating website on WordPress is safe and secure to operate. You don’t need to worry about anything but still it is suggested wordpress official to update your site regularly with latest WordPress version to avoid hacking and attackers.

Question: Is it possible to SEO a WordPress site to show it on Google first page?


WordPress has an in-built SEO search engine benefit. You can also have an additional plug-in in WordPress to help with SEO and rank on a popular search engine like Google.

Question: What is plugin in WordPress?


Plugins are short set of program which help to extend and add to the functionality that already exists in WordPress. The core of WordPress is designed to be lean and lightweight, Plugins then offer custom functions and features so that each user can tailor their site to their specific needs.

Question: Do you need to have a blog in order to use WordPress for site?


WordPress was originally used as blogging software though it has since become popular for website also. It is not necessary to have a blog to use wordpress. Still having blog is commendable as it will help in search engine optimization.

Question: What is the prefix of wordpress tables by default?


wp_ is the By default prefix for wordpress.

Question: Why does WordPress use MySQL?


MySQL is pen source and free of cost widely available database server and it is extremely fast. it is supported by many low-cost Linux hosts so its easy for anyone to host their website in very low cost.

Question: What is WordPress loop?


To display post WordPress use PHP code, this code is known as loop.

Question: In WordPress objects are passed by value or by reference?


In WordPress, all objects are passed by value.

Question: How can you call a constructor for a parent class?


By using this way you can call the parent constructor
Parents:: constructor($value)
 

Question: What are posts in WordPress.?


Posts allow you to write a blog and post it on your site. They are listed in reverse chronological order in front page of your blog.

Question: What are pages in WordPress.?


Pages are different from posts. They are static and they do not change often. You can add pages containing information about you and your site.

Question: Is there any Alternative CMS of WordPress?


Yes many Joomla, Drupal,Ghost, Silver Stripe etc.

Question: What is the use of Slug field in tags?


It is used to specify the tags URL.

Question: What is wordPress Category?


Category is used to indicate sections of your site and group related posts. It sorts the group content into different sections. It is a very convenient way to organize the posts.

Question: What is WYSIWYG Editor?


WYSIWYG Editor is similar to a word processor interface where we can edit the contents of the article.

Question: Does WordPress have cookies?


Yes, WordPress have cookies and WordPress uses cookies for verification of users while logged in.

 


remove extra lines spaces in sublime

Select the text

Press:

Ctrl + H on PC, or
Command + Alt + F on Mac or
Click Find->Replace.

Make sure you have selected 'regular expression' by pressing:

          Alt + R on PC or
    Command + Alt + R or
    Click .* in the Find box.


Find what: ^\n

Replace With: (nothing, leave in blank).

How to Increase file import size limit in phpMyAdmin

Hello. I face problem while uploading files because of its size. The default file import/upload size in phpMyAdmin is 2MB, For increasing file import size You need to make some changes in php.ini file and restart apache server. After changing following parameter you’ll able to import big .sql file easily.
Here i am going to take example of ubantu LAMP server , find php.ini file and open it on any text editor.
sudo vim /etc/php5/apache2/php.ini
 

if you are using any other server like WAMP, XAMPP similar find php.ini and open it on text editor
Find and Change these values in php.ini file.
post_max_size = 1024M 
upload_max_filesize = 1024M 
max_execution_time = 5000 
max_input_time = 5000 
memory_limit = 1024M
 
Note: don’t forget to allocate larger value to memory_limit then post_max_size.
Finally restart apache server and your new upload size will be visible on phpMyAdmin file import section, You you can upload larger file.
sudo service apache2 restart
 

 

 

Friday, February 3, 2017

Server side email validation in php with filter_var

Validating email address on server side is more secure way to prevent from span entry, Some people disabled javascript on their browser and enter wrong or garbage username/email address, So validating email on server side is good approach.

You can use the filter_var() function, which gives you a lot of handy validation and more options.
Note: PHP 5.2.0 or higher is required for the filter_var function. Here is the quick function in php to validate email address in single line.
function checkValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
 
Above function will validate email like “chirag@gmail” as a valid email, In Standard HTML5 email validation also pass this string too as a valid email, You need to add some extra security in your function to validate TLS so that you can get more filtered email data.
Email with TLS validation.

function checkValidEmail($email){ 
   return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email);
}
 

Example:

echo checkValidEmail('chirag@gmail'); // false
echo checkValidEmail('chirag@gmail.'); // false  
echo checkValidEmail('chirag@gmail.com'); // true  
echo checkValidEmail('chirag@gmail.com.'); // false
 

 

Thursday, February 2, 2017

The best way to SEO a wordpress site

Get Yoast all-in-one, configure it with Google Webmaster Tools and Analytics. Secure it. Harden it. Nothing worse for SEO than getting hacked.

No website can perform better without SEO. In fact, SEO becomes important to get the web visibility. It is true that not every website can rank on the search engine with every keyword yet, we could optimize some of the keywords in a way to get organic traffic.
SEO can be performed on any of the platforms yet, Word press seems to be more effective due to easy CMS based Systems and Free Plug-Ins. Here are some of the optimum ways to optimize the website:-
1) First of all, you are required to Install and activate the Yoast SEO Plug-in which is quite easy to use and understand.
2) Optimize the Pages, Posts, Images through Title, Meta tags, Meta description, Alt tags etc.
3) Check out the quality of content and maintain optimum keyword density. Keyword stuffing should be avoided.
4) Integrate Blog section and post content on weekly basis. Make sure to optimize each blog post and images
5) Perform Interlinking, yet avoid too much or interlinking.
6) Fetch Homepage URL and relevant URL through off page techniques like Directory submission, social bookmarking, business listing, profiling and all.
7) Make more emphasis on Content marketing through Article Writing, Blog Writing, and Guest Post etc.
Like another website, Word Press can be promoted easily due to its user-friendly, mobile-friendly and SEO-friendly activities.


To get setup
  1. Google Webmasters - Support, Learn, Connect & Search Console - Google
  2. Google Analytics
  3. Use PageSpeed Insights to measure page load times - very important
  4. All In One SEO Pack to WordPress SEO Migration • Yoast
  5. Create a twitter, facebook, LinkedIn page(s) as necessary
  6. Join some subject matter fora (forums), groups etc on Linkedin, G+
  7. Setup a ranking report to see how you’re site is doing
  8. Consider buying into a tool like service for competitors research, shows organic and Ads keywords for any site or domain
When you write a post
  1. Think of an interesting title - with the most attractive keywords or ideas or elements
  2. Add an image; optimize the site for social sharing
    1. Alt Text
  3. Set a relevent category
  4. Share it and post it on some of your channels