Get All WordPress Navigation Menus list

If you are trying to create a new options in metaboxes oo in theme options to get all the wordpress menu list.Use the Below code.

<?php
$display_menus = get_terms( 'nav_menu' );
foreach($display_menus as $menu)
{
echo $menu->name;
}
?>

!Important Update Your All in One SEO Pack WordPress Plugin Now

All wordpress sites are getting hacked for the users who are using older version of  " All in One Seo Plugin".  The code in the plugin had couple of security issues that enabled hackers to:
(1) Conduct privilege escalation
(2) Cross site scripting (XSS) attacks
So to Protect your Website Update to latest version Now

How to reduce your site load time in WordPress?

By using different plugins, adding larger number of scripts in your theme and using larger images may lead in increasing the site load time. To avoid this we need to follow few steps.

1.Check your Hosting quality.
2.Use sprites for background images in Css.
3.Use Best and quality plugins.
4.Try to reduce external scripts running on the site.
5.Keep you custom scripts in footer.php.
6.Keep you main style sheet at top of all scripts and links.

Finally us this code, Paste this code in your site ".htaccess".

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/html M3600
    ExpiresByType text/css M3600
    ExpiresByType application/x-javascript M3600
    ExpiresByType image/bmp M3600
    ExpiresByType image/gif M3600
    ExpiresByType image/x-icon M3600
    ExpiresByType image/jpeg M3600
</IfModule>

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css application/x-javascript text/plain text/xml image/x-icon
</IfModule>

(Note: Backup up your .htaccess )

How to Assign Category to a Post Automatically

Copy and Paste the Below code in you theme functions.php.

 function auto_add_category ($post_id = 0) {
     if (!$post_id) return;
     $tag_categories = array ( //  add multiple items as shown 'Tag Name' => 'Categroy Name'
       'toys' => 'Kids',
       'apple' => 'Fruits',
     );
     $post_tags = get_the_tags($post_id);
     foreach ($post_tags as $tag) {
       if ($tag_categories[$tag->name] ) {
         $cat_id = get_cat_ID($tag_categories[$tag->name]);
         if ($cat_id) {
           $result =  wp_set_post_terms( $post_id, $tags = $cat_id, $taxonomy = 'category', $append = true );
         }
       }
     }
   }
add_action('publish_post','auto_add_category');
?>

Add SSL Secure to Specific Page

HTTPS (Secure Hypertext Transfer Protocol) is used instead of HTTP top protect your webpage, If your website has payment transactions with a 3rd party payment gateway like "Authorize.Net, Paypal.."

I recommend you to activate HTTPS for Better Protection.

To have HTTPS, SSL Certificate is needed to be installed on your server.
Activating SSL on your specific pages, Just copy and paste the below code in your themes functions.php 

function wordpress_ssl( $wp_ssl, $post_id = 0, $url = '' ) {
    if ( $post_id == 25 ) { // change your page ID here
        return true;
    }
    return $wp_ssl;
}
add_filter('wp_ssl' , 'wordpress_ssl', 10, 3);

Display Posts for Specific Category

Normally WordPress default functionality display all posts of all category, But if we need to display only posts of certain or one category, Use the below code.

Replace '2' with your Category id.

<?php query_posts('cat=2'.'&orderby=date&order=asc'); ?> // 2 is the Category id

<?php while (have_posts()) : the_post(); ?>

<h2><?php the_title(); ?></h2>

<?php the_content(); ?>

<?php endwhile; ?>

Disable Admin panel link for users

If your website has multiple users with different roles, We can disable Admin link to users other then admin using below code.

Copy and Paste Below code in your Theme's 'function.php'

<?php if (current_user_can("manage_options")) : ?>
       <a href="<?php echo bloginfo('url') ?>/wp-admin/">Admin</a>
<?php endif; ?>

Edmunds Vehicle API with Jquery




To get all Vehicle Details (New, Used, Future) using Jquery , Use the below code.

<!--Form Details to display year/make/model in dropdown -->

<form method="POST" action="one123.php">
       <select id="ajYears" name="ajYears">
        </select>
         <select id="ajMakes" name="makes" disabled="disabled">
            <option>Select Make</option>
        </select>
        <select id="ajModels" name="models" disabled="disabled">
            <option>Select Model</option>
        </select>
        <select id="ajStyles" name="styles" disabled="disabled">
            <option>Select Trim</option>
        </select>
        <input type="submit" value="submit">
</form>

<!--Script to fetch details from API-->

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
    jQuery.noConflict();
</script>

<!-- js code -->

<script>
  <script>
    var protoCall = "https://";
    var host = "api.edmunds.com";

        // Make sure to change the API KEY
    var apiKey = "v4hq7w7nac87ehk9exfvasu5";
    var fmt = "json";
    var standardParams = "&fmt=" + fmt +  "&api_key=" + apiKey + "&callback=?";
    var $yearSelect = jQuery('#ajYears');
    var $makeSelect = jQuery('#ajMakes');
    var $modelSelect = jQuery('#ajModels');
    var $styleSelect = jQuery('#ajStyles');

    // lets bind some events on document.ready.
    jQuery(function(){

        $yearSelect.on('change', function() { getMakeModelsByYear()});
        $makeSelect.on('change', function() { enableModelDropdown() });
        $modelSelect.on('change', function() { getStyles();  });
$styleSelect.on('change', function() { jQuery('.veh_submit').removeAttr("disabled");  });

        // lets build the year drop down.
        ajEdmundsBuildYear();

    });

    // Method to build the year drop down.
    function ajEdmundsBuildYear()
    {
        var baseYear = 1990,
            endYear = new Date().getFullYear();
        $yearSelect.empty();
        $yearSelect.append('<option value="-1">Select Year</option>');
        for(var yyyy=baseYear; yyyy<=endYear; yyyy++)
        {
            $yearSelect.append('<option value="' + yyyy + '">' + yyyy +'</option>');
        }
    }

    // get the makes and modals for a year in one go, but we don't display modals here...
    function getMakeModelsByYear()
    {
$makeSelect.empty();
$modelSelect.empty();
$styleSelect.empty();
         $makeSelect.append('<option value="-1">Select Make</option>');
$modelSelect.append('<option value="-1">Select Modal</option>');
$styleSelect.append('<option value="-1">Select Style</option>');
$makeSelect.attr('disabled','disabled');
$modelSelect.attr('disabled','disabled');
$styleSelect.attr('disabled','disabled');
        var year = $yearSelect.val(),
            endPoint = "/api/vehicle/v2/makes",
            view = "basic",
            options = "year=" + year + "&view=" + view + standardParams,
            postURL = protoCall + host + endPoint + "?" + options;
        jQuery.getJSON(postURL,
            function(data) {
                 // clear the make drop down... re add the first option... remove dsiabled attr.
                 $makeSelect.empty();
                 $makeSelect.append('<option value="-1">Select Make</option>');
                 $makeSelect.removeAttr('disabled');
             

                 // loop the makes... each make contains model... add the make in make drop down.
                 jQuery.each(data.makes, function(i, val) {
                      make = data.makes[i];
                      $makeSelect.append('<option value="' + make.niceName + '">' + make.name + '</option>');
                 });
            });
    }

    // since we already grabed the models...
    // now just matter of showing only the matching models for a make.
    function enableModelDropdown()
    {

// clear the Style down... re add the first option... add dsiabled attr.
$styleSelect.empty();
$styleSelect.append('<option value="-1">Select Style</option>');
    $styleSelect.attr('disabled','disabled');
var make1 =  $makeSelect.val();
var year = $yearSelect.val(),
            endPoint = "/api/vehicle/v2/makes",
            view = "basic",
            options = "year=" + year + "&view=" + view + standardParams,
            postURL = protoCall + host + endPoint + "?" + options;
        jQuery.getJSON(postURL,
            function(data) {
//let's empty our modal
$modelSelect.empty();
// loop the makes... each make contains model... add the modal in modal drop down.
//re add the first option
                 $modelSelect.append('<option value="-1">Select Model</option>');
                 jQuery.each(data.makes, function(i, val) {
                      make = data.makes[i];

// loop the makes... each make contains model... add the modal in modal drop down but it depends on make value we select previously
                      jQuery.each(make.models, function(x, val){
                           model = make.models[x];
  if(make1 == make.niceName){ // here is the logic
                           $modelSelect.append('<option make="' + make.niceName +'" value="' + model.niceName + '">' + model.name + '</option>');
  }
                      });
                 });
            });

        $modelSelect.removeAttr('disabled');

    }

    // grab the styles... pretty much same as
    // getMakeModelsByYear()
    function getStyles()
    {

        var year = $yearSelect.val(),
            make = $makeSelect.val(),
            model = $modelSelect.val(),
            endPoint = "/api/vehicle/v2/" + make + "/" + model + "/" + year + "/styles",
            view = "basic",
            options = "view=" + view + standardParams,
            postURL = protoCall + host + endPoint + "?" +  options;
        jQuery.getJSON(postURL,
            function(data) {
                 $styleSelect.empty();
                 $styleSelect.removeAttr('disabled');

                 $styleSelect.append('<option value="-1">Select Style</option>');
                 jQuery.each(data.styles, function(i, val) {
                      style = data.styles[i];
                      $styleSelect.append("<option value='" + style.id + "'>" + style.name + "</option>");
                 });
            });
    }
</script>



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

Hello Mates here is the second step

<?php
if(isset($_POST['submit'])) {
$to = 'youremial@gmail.com'; // Change this to your email
$subject = ''.$_POST['m_phone'].'';
$subject_sucess = "Edmunds Vehicle API with Jquery -  Output";
$ajYears = $_POST['ajYears'];
$ajMakes = $_POST['ajMakes'];
$ajModels = $_POST['ajModels'];
$ajStyles = $_POST['ajStyles'];
$mycar = $_POST['mycar'];
$approx_milage = $_POST['approx_milage'];
$email = $_POST['email'];
$h_phone = $_POST['h_phone'];
$m_phone = $_POST['m_phone'];
$fname = $_POST['fname'];
$l_name = $_POST['l_name'];
$add1 = $_POST['add1'];
$add2 = $_POST['add2'];
$city = $_POST['city'];
$r_state = $_POST['r_state'];
$zip = $_POST['zip'];
$loanamont = $_POST['loanamont'];
$from = ''.$fname.'<'.$email.'>';

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Create email headers
$headers .= 'From: '.$fname.' <youremial@yourwebistename.com>'. "\r\n"; // Change this to your website email
    'Reply-To: '.$email."\r\n" .
    'X-Mailer: PHP/' . phpversion();

// To send HTML mail, the Content-type header must be set
$headers_success  = 'MIME-Version: 1.0' . "\r\n";
$headers_success .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Create email headers
$headers_success .= 'From: Edmunds Vehicle API <youremial@yourwebistename.com>'. "\r\n"; // Change this to your website email
    'Reply-To: '.$email."\r\n" .
    'X-Mailer: PHP/' . phpversion();

// Compose a simple HTML email message
$message = '<b>Year:</b> '.$ajYears.'<br>
<b>Make:</b> '.$ajMakes.'<br>
<b>Model:</b> '.$ajModels.'<br>
<b>Style:</b> '.$ajStyles.'<br>
<b>My car does not appear:</b> '.$mycar.'<br>
<b>Approx. Mileage:</b> '.$approx_milage.'<br>
<b>Email:</b> '.$email.'<br>
<b>Home Phone:</b> '.$h_phone.'<br>
<b>Mobile Phone:</b> '.$m_phone.'<br>
<b>First Name:</b> '.$fname.'<br>
<b>Last Name:</b> '.$l_name.'<br>
<b>Address Line 1:</b> '.$add1.'<br>
<b>Address Line 2:</b> '.$add2.'<br>
<b>City:</b> '.$city.'<br>
<b>Residence State:</b> '.$r_state.'<br>
<b>Zip Code:</b> '.$zip.'<br>
<b>Loan Amount Requested:</b> '.$loanamont.'';

$message_sucess='Thank you for filling out, We will be happy to assist you.';

// Sending email
if(mail($to, $subject, $message, $headers)){ mail($email, $subject_sucess, $message_sucess, $headers_success); ?>
    <script>window.location.assign("http://www.yourwebistename.com");</script>
<?php }
else {echo "mail not sent";}
}
?>

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

If no email functionality is required you can use this Code.

1. Update your HTML with the below

<!--Form Details to display year/make/model in dropdown -->

       <select id="ajYears" name="ajYears">
        </select>
         <select id="ajMakes" name="makes" disabled="disabled">
            <option>Select Make</option>
        </select>
        <select id="ajModels" name="models" disabled="disabled">
            <option>Select Model</option>
        </select>
        <select id="ajStyles" name="styles" disabled="disabled">
            <option>Select Style</option>
        </select>
        <input type="submit" value="Submit" class="veh_submit">

<!-- output Table -->
<table width="735" border="0"  class="output" cellpadding="0" cellspacing="0" style="display:none;">
<tr>
<td colspan="2" style="text-align:center"><strong>Vehicle Information</strong></td>
</tr>
<tr>
<td><strong>Year</strong></td>
<td class="year">Empty</td>
</tr>
<tr>
<td><strong>Make</strong></td>
<td class="make">Empty</td>
</tr>
<tr>
<td><strong>Modal</strong></td>
<td class="modal">Empty</td>
</tr>
<tr>
<td><strong>Style</strong></td>
<td class="style">Empty</td>
</tr>
</table>
</div>

2. Add this script after </body> tab

<script>
// just to display the output
        jQuery('.veh_submit').on("click",(function(){

var ajYears = jQuery("#ajYears").val();
var ajMakes = jQuery("#ajMakes").val();
var ajModels = jQuery("#ajModels").val();
var ajStyles = jQuery("#ajStyles option:selected").text();

//Basic Validation

if(ajYears =='' || ajYears==-1)
{
   alert("Please Select a Year");
exit;
}
else if(ajMakes =='' || ajMakes==-1)
{
alert("Please Select a Make");
exit;
}
else if(ajModels =='' || ajModels==-1)
{
alert("Please Select a Model");
exit;
}
else if(ajStyles =='' || ajStyles=="Select Style")
{
alert("Please Select a Style");
exit;
}

jQuery('.output').show();
jQuery('.year').html(ajYears);
jQuery('.make').html(ajMakes);
jQuery('.modal').html(ajModels);
jQuery('.style').html(ajStyles);

}));

</script>


Get Hosting and Domains for Best prices  at  http://webservices.redtreetechnology.com/

Reference url:  http://developer.edmunds.com/faq.html

How to Create Custom Posts without using plugins

Step1: Copy and paste the Below code in your theme "function.php". Here i am using this code to create Cusotm Post for "Testimonials", We can Rename it as required

<?php add_action('init', 'testimonials_init');
function testimonials_init()
{
    $feature_labels = array(
        'name' => _x('Testimonials', 'post type general name'), // Name which displays in dashboard
        'singular_name' => _x('Testimonial', 'post type singular name'),
        'all_items' => __('All Testimonials'),
        'add_new' => _x('Add new Testimonial', 'director'),
        'add_new_item' => __('Add new Testimonial'),
        'edit_item' => __('Edit Testimonial'),
        'new_item' => __('New Testimonial'),
        'view_item' => __('View Testimonial'),
        'search_items' => __('Search in Testimonial'),
        'not_found' =>  __('No Testimonial found'),
        'not_found_in_trash' => __('No Testimonial found in trash'),
        'parent_item_colon' => ''
    );
    $args = array(
        'labels' => $feature_labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => 5,
        'supports' => array('title', 'editor','thumbnail'), //  Delete this if thumbnail is not required
        'has_archive' => 'testimonial'
    );
    register_post_type('testimonial',$args); // Post type ID
}
?>

Step2: Copy  and paste this code in your Template to display posts  
Note: Change "post_type=testimonial" if you changed it in the above code

<?php
$my_query = new WP_Query('post_type=testimonial&posts_per_page=-1'); // "-1" describs to display all posts , You can Restrict posts by using positive values
while ($my_query->have_posts()) : $my_query->the_post();
?>
 <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> // Post Title
<div class="thumbnail">
<?php the_post_thumbnail();?> // Post Thumbnail
</div>
<div class="entry">
      <?php the_content(); ?> // Post Content
    </div>
<?php endwhile; ?>
   

Create Custom Fileds in Wordpress

Without using any plugin we can create custom fields in WordPress.

In WordPress dashboard at top right corner you can see "Screen options" . Click on it and check "Custom Fields" to activate it . (But you can see "Custom Fields" option only in Post/Page Edit mode)

Custom Fields




In Page Edit Mode under content Editor you can see a Meta box "Custom Fields", In this we can see 2 fields "Name" and "value". "Name" will be your ID and Value will be the output. Create a custom field and update your post or page .

Display custom field

1. <?php the_meta(); ?> //  this displays all custom fields created in a page

place this in your header.php . I am using this as unique Slogan for every page.  

2.If you wanted to display value of one specific custom field, use the code shown below

<?php echo get_post_meta($post->ID, 'demo', true); ?> // "demo" would be ID of custom field

3. Display multiple values of same custom field ID, use this code

<?php $c_demo = get_post_meta($post->ID, 'demo', false); ?> // "demo" would be ID of custom field
<ul>
    <?php foreach($c_demo as $c_demo_display) {
        echo '<li>'.$c_demo_display.'</li>';
    } ?>
</ul>

4. Display output only if custom field exists

<?php

$logic = get_post_meta($post->ID, 'demo', true);

if($logic!='')
{
echo $logic;
}
?>







Create Shortcode in Wordpress

You can create any shortcode in wordpress by using below code format

Here i am showing you an example Shortcode for "Date".

function cdate_shortcode() {
  $shortdate = get_the_date('l, F j, Y');
  return $shortdate;
}
add_shortcode('shortdate', 'cdate_shortcode');

Place the above code in your theme's function.php file

Use [shortdate] in your Posts/pages.

Restrict content in Post or Page for Wordpress

Generally we display our content using "the_content();". But this displays entire content in Post or page.
To restrict this without using complicated code, Use the below code

$rest_content = the_content();
$content_result = substr($rest_content,'0','200') // 200 specifies the characters to display
echo $content_result;

Move your wp-content folder in Wordpress

To Make your website more secure from Hackers,  We can move wp-content folder which  contains your themes, plugins and uploads. Few plugins uses wp-content to store

their cache data.So we can make it more difficult for people to find your wp-content directory by moving it to another area of your website.

To Move wp-content folder to another location, Add this code into your wp-config.php file


define( 'WP_CONTENT_DIR', dirname(__FILE__) . '/customfolder/wp-content' );

"Replace customfolder with your folder name (don't use special characters or Capital letters as your Folder name) "

You can add new location using the URL as shown below

define( 'WP_CONTENT_URL', 'http://www.mywebsite.com/customfolder/wp-content' );

Otherwise you to rename your wp-content folder using below code

define ('WP_CONTENT_FOLDERNAME', 'customfolder');

Moving or Renaming your wp-content folder can make WordPress website more safer, But not always because many WordPress plugin developers continue to write “wp-content” in their plugin code which may effect on plugin functionality. For such plugins we need to update manually if securing your website is your main priority!!.

Automatically Empty your Trash in WordPress

For Security purpose WordPress will keep a copy of deleted posts, pages, Comments and images in Trash until you delete them permanently. As per WordPress

Functionality Trash will clear automatically after 30 days. But this can be reduced by adding a small code into your wp-config.php file.

define ('EMPTY_TRASH_DAYS', 7); // Change 7 to number of days required

If you want make it clear, So that no unnecessary items are stored in your Trash, you can disable the trash system completely by adding this line of code to your wp-config.php file.

define ('EMPTY_TRASH_DAYS', 0);

Note:
1. Don't use Both the codes shown above at a time in wp-config.php file, however it takes top line as priority in PHP

Custom Captcha for Contact Form 7

Custom Captcha for Contact From 7 in wordpress is so simple . At present Contact From 7 uses "Really Simple Captcha" plugin to display a Captcha. I will us use the same plugin , But with some minor modifications.

Step 1: Install Contact Form 7 plugin
Step 2: Install Really Simple Captcha plugin
Step 3: We will start with editing Contact Form 7. Open contact-form-7\modules\captcha.php from your Plugins Folder.

Go to line #36  and replace the array with below code.

$op = array(
'img_size' => array( 150, 24 ),
'base' => array( 6, 18 ),
'font_size' => 14,
'font_char_width' => 15 );

If you are using a Multi Site you can control Captcha for specific website using the code shown below.

$current_blog_id = $GLOBALS['blog_id'];
if ($current_blog_id == 120) { // Change your Blog Id
$op = array( // Default
'img_size' => array( 150, 24 ),
'base' => array( 6, 18 ),
'font_size' => 14,
'font_char_width' => 15 );
}else{
$op = array(
'img_size' => array( 72, 24 ),
'base' => array( 6, 18 ),
'font_size' => 14,
'font_char_width' => 15);
}

Step4: Now add the below code into your theme's function.php to disable updates

function filter-plugin_updates ($value){
unset($value ->response['contact-form-7/wp-contact-form-7.php']);
unset($value ->response['really-simple-captcha/really-simple-captcha.php']);
return $value;
}
add_filter('site_transient_update_plugins', 'filter-plugin_updates' );

Step5: Open "really-simple-captcha.php" from Really Simple Captcha Plugin Folder.

Go to line #39 and replace with code below

$this->char_length = 8; // Edit length of Captcha (I am displaying 8 characters)

If you are using a Multi Site use this code
$current_blog_id = $GLOBALS['blog_id'];

if ($current_blog_id == 120) { // Edit your Blog id
$this->char_length = 8;
}else{
$this->char_length = 4;
}

Step6:

Go to line #52 and replace with the code below

$this->img_size = array( 150, 24 ); // height and width of Cpatch image

If you are using a Multi Site use this code

if ($current_blog_id == 120) {
$this->img_size = array( 150, 24 ); // height and width of Cpatch image
}else{
$this->img_size = array( 72, 24 );
}

Step7: Done !!