Search only post type in wordpress

By default wordpress search provides a searching function on whole site whether it is pages or post type. In order to make the search only post type in wordpress, below is the code you need to copy and paste it in to your function.php file.

 function filter_search($query) {
if ($query->is_search) {
  $query->set('post_type', array('post','page'));
};
return $query;
};
add_filter('pre_get_posts', 'filter_search');
?>
Notice the line that says
 $query->set('post_type',array('post','page'));
We can filter the search results by changing the values in the array variable. Right now it is set to display posts and pages but you can modify it to display anything we required.

Create a coupon programatically in WooCommerce

We will need to add this code to our child theme’s functions.php file or via a plugin that allows custom functions to be added. We always have to remember, we don’t have to add custom code directly to our parent theme’s functions.php file as this will be wiped entirely when we update the theme.

/**
 * Create a coupon programatically
 */
$coupon_code = 'UNIQUECODE'; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product
     
$coupon = array(
 'post_title' => $coupon_code,
 'post_content' => '',
 'post_status' => 'publish',
 'post_author' => 1,
 'post_type'  => 'shop_coupon'
);
     
$new_coupon_id = wp_insert_post( $coupon );
     
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'no' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );

WooCommerce Account Page Custom Endpoint

We can do it using below simple steps. We have to add the below code given in steps in our theme functions.php or in plugin code.

Step 1: In this post, we will see how we can add custom endpoint to my account page in front means one new our own page like order, download (default one’s). To do this, first we’ll add rewrite endpoint using WordPress function ‘add_rewrite_endpoint’ on ‘init’ hook.

function aft_custom_endpoint() {
  add_rewrite_endpoint( 'custom', EP_ROOT | EP_PAGES );
}
 
add_action( 'init', 'aft_custom_endpoint' );

Step 2: Now, we will add menu item for this custom endpoint on WooCommerce My Account page menu so that we can access easily. For this we’ll use ‘woocommerce_account_menu_items’ filter.

add_filter( 'woocommerce_account_menu_items', 'aft_new_menu_items' );
 
/**
* Insert the new endpoint into the My Account menu.
*
* @param array $items
* @return array
*/
function aft_new_menu_items( $items ) {
    $items[ 'custom' ] = __( 'Custom', 'webkul' );
    return $items;
}

The above code will add one more menu item named Custom at the end of my account page menu list.

Step 3: The endpoint has been added, menu item also added, now next thing will be, how can we add content to this new (say) page..? Not to worry, WooCommerce provide the hook using which we can add content –

$endpoint = 'custom';
 
add_action( 'woocommerce_account_' . $endpoint .  '_endpoint', 'aft_endpoint_content' );
 
function aft_endpoint_content() {
    //content goes here
    echo '//content goes here';    
}

How To Change the Author URL Slug in wordpress


Are you looking for a way to change the author URL slug? This snippet will change the default slug, mysite.com/author/name, to mysite.com/profile/name. However, you can change this to anything that you would like.
Instructions:
  1. Add this code to your theme’s functions.php file or in site-specific plugin.
  2. Change profile in line 4 to any name you would like.
add_action('init', 'cng_author_base');
function cng_author_base() {
    global $wp_rewrite;
    $author_slug = 'profile'; // change slug name
    $wp_rewrite->author_base = $author_slug;
}
Note: If changes is not reflecting after adding the code, you can check after updating permalink setting from back-end.

How to check custom fields exists or not

Add a custom field

Now lets just add a custom fields value to our post. After checking the custom fields checkbox, scroll down to the page to see the Custom Fields box. Write your first custom fields name under the Name. It will be a kind of variable to call in our template file. After that write a value you want to display in your post. It should be done under the Value tab.

Get custom fields value to our post

To get the custom fields value we do not need to add any function into the function.php file. Its quite easy to get it by the simple wordperss function.
Just copy the below code into your theme or where you want to display the value.

echo get_post_meta($post->ID, 'Your Custom Fields Name', true);

Check if the custom fields exists or not

With the help of of some if else conditional statement we can check weather the our custom fields name has a value or not.

$key = 'sub-heading';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta != '') { 
 echo '

'.get_post_meta($post->ID, 'sub-heading', true).'

'; }

Adding CC and BCC contact form 7

CC and BCC are emails general header object in which CC means to be Carbon Copy and BCC means Blind Carbon Copy. CC consists of a email id. Adding CC and Bcc contact form 7 is very easy.

CC: example@xyz.com

When an email is composed to send to your client and you want the same email to be sent to you secondary email ID at the same time CC is used. BCC is like CC but it hide the email id of secondary.

One of very popular plugin called contact form 7 has an admin interface that allows you to manage your contact form via admin. It is necessary to know how to add CC and BCC to your contact form 7 via admin panel. You can follow these below steps to accomplished this easy task.

  • Login to your Dashboard
  • Find contact tab on the left panel
  • Click on specific contact form from the form listing.
  • Now click on Mail tab and go to Additional Headers section.
  • Now add your cc email id by following the format ( CC: your-email-id@hosting.com)
  • Scroll down to click on save

HTML5 default validation for confirm password

In this section, we am going to see how you we easily validating HTML5 default validation for confirm the password. Generally in HTML5 when we create a form we simply write “required” attribute to the form element and it starts validating itself without other javascript code. But for confirm password validation we would required to add few lines of code that will set the validation in the default way.

HTML

Confirm password with HTML5

JAVASCRIPT

var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");

function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}

password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;

Wordpress Update User's Password with PHP

It worked for me to update 'user_pass' using both update_user_meta and wp_update_user:


update_user_meta($user_id, 'user_pass', $newpassword);
wp_update_user( array ('ID' => $user_id, 'user_pass' => $newpassword) ) ;

Get first letter of each word for a given string in PHP

QUESTION:How would I get the first letter of each word for a given string?

$string = "This Is The TEST String";
$result = "TITTS";

ANSWER: explode() on the spaces, then you use the [] notation to access the resultant strings as arrays:

$words = explode(" ", "This Is The TEST String");
$acronym = "";

foreach ($words as $w) {
  $acronym .= $w[0];
}

If you have an expectation that multiple spaces may separate words, switch instead to preg_split()

$words = preg_split("/\s+/", "This Is The TEST String");

Or if characters other than whitespace delimit words (-,_) for example, use preg_split() as well:

// Delimit by multiple spaces, hyphen, underscore, comma
$words = preg_split("/[\s,_-]+/", "This Is The TEST String");

How to Allow Only One Checkbox to be Checked using jQuery

Generally, we use radio buttons to let a user select ONE option from a limited number of choices. Most of the cases radio buttons are ideal to select a single option from a group of the options. But sometimes you required to use the checkbox to do the same functionality like a radio button. If you want to allow the user to check only one checkbox from a group of the checkboxes, it can be done easily using jQuery.
How to Allow Only One Checkbox to be Checked using jQuery
At first, include the jQuery library.

Use the following code to allow only one checkbox to be checked using jQuery.

HTML

 Male
 Female
 Other

JavaScript

$(document).ready(function(){
    $('input:checkbox').click(function() {
        $('input:checkbox').not(this).prop('checked', false);
    });
});

Remove Contact Form 7 CSS and JS Unless Contact form 7 shortcode is used in the page

Remove Contact Form 7 CSS and JS Unless Contact form 7 shortcode is used in the page
Question :
Want to show the css and javascript only when the shortcode is used in that page. If the short code not present in the wordpress page then the js and css of contact form should not be shown.
Solution code for : Remove Contact Form 7 CSS and JS Unless Contact form 7 shortcode is used in the page
Here is the answer for your question. If there is not shortcode the css and js of contact form will be removed and if there is shortcode css and js will be added.
function aft_lwp_contactform_css_js() {
    global $post;
    if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'contact-form-7') ) {
        wp_enqueue_script('contact-form-7');
         wp_enqueue_style('contact-form-7');

    }else{
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_style( 'contact-form-7' );
    }
}
add_action( 'wp_enqueue_scripts', 'aft_lwp_contactform_css_js');

Fetch contact-form-7 id to another plugin

Fetch contact-form-7 id to another plugin
Question :
How to fetch contact-form-7 forms ID, to another plugin?
I want to get forms id and using that id, I will give some effect to that form, please tell me how to fetch form id from contact-form-7, to another plugin in wordpress.
Solution code for : Fetch contact-form-7 id to another plugin
Actually in contact form 7,the post type is wpcf7_contact_form So you can use this bellow code . In tis code the function return an array of all contact form's id.
function get_cf7_IDS(){
   $cf7_id_array =array();
    if ( post_type_exists( 'wpcf7_contact_form' ) ) {
      $args = array(
        'post_type' => 'wpcf7_contact_form',
        'posts_per_page'=>-1,
      );
      $the_query = new WP_Query( $args );
      if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
          $the_query->the_post();
          $cf7_id_array[]= get_the_ID(); 
        }
        wp_reset_postdata();
      }   
  }
  return $cf7_id_array; //RETURN THE ARRAY OF IDS
}
Then use this function to get all ides in array get_cf7_IDS(). Then let me know the result.

How to hook into Contact Form 7 Before Send

Question :
Solution code for : How to hook into Contact Form 7 Before Send

How to hook into Contact Form 7 Before Send

I had to do this to prevent Email from being sent. Hope it helps.
/*
    Prevent the email sending step for specific form
*/
add_action("wpcf7_before_send_mail", "wpcf7_do_something_else");  
function wpcf7_do_something_else($cf7) {
    // get the contact form object
    $wpcf = WPCF7_ContactForm::get_current();

    // if you wanna check the ID of the Form $wpcf->id

    if (/*Perform check here*/) {
        // If you want to skip mailing the data, you can do it...  
        $wpcf->skip_mail = true;    
    }

    return $wpcf;
}

Contact Form 7 AJAX Callback

Question :
Been searching around on this for a while and can't come up with any documentation to outline what i want to achieve.
I'm using wordpress and the Contact Form 7 plugin, all is working perfectly, what i want to achieve is to run some particular javascript upon form submit, I know we can use "on_sent_ok:" in the additional settings, but this only performs if the form is actually submitted.
What I'd like to do is to do some other javascript when the form doesn't submit ok, which throws the user back to the section which didn't validate.
Contact Form 7 AJAX Callback
Solution code for : Contact Form 7 AJAX Callback
Given the variety of responses on this topic the plugin developer seems to change their mind about how this should work every 5 minutes.
document.addEventListener( 'wpcf7mailsent', function( event ) {
  alert( "Fire!" );
}, false );
And the valid events are:
  • wpcf7invalid — Fires when an Ajax form submission has completed successfully, but mail hasn’t been sent because there are fields with invalid input.
  • wpcf7spam — Fires when an Ajax form submission has completed successfully, but mail hasn’t been sent because a possible spam activity has been detected.
  • wpcf7mailsent — Fires when an Ajax form submission has completed successfully, and mail has been sent.
  • wpcf7mailfailed — Fires when an Ajax form submission has completed successfully, but it has failed in sending mail.
  • wpcf7submit — Fires when an Ajax form submission has completed successfully, regardless of other incidents.
Reference: https://contactform7.com/dom-events/

Redirect contact form 7 with javascript

Question :
I do not want to use the additional setting because its filled with a bunch of analytics code. I want to my javascript function to fire when the button is clicked. example the contact form 7's button ID is #aft_submit.
Redirect contact form 7 with javascript
Soution code for : Redirect contact form 7 with javascript
Seen as you are using jquery anyway, you can add the click on the submit button like this
jQuery( document ).ready(function() {
    jQuery("#aft_submit").on('click', function(e){
        e.preventDefault();
        window.location.href  = "http://url-to-redirect.com";
    });
}
You'll need to prevent the default 'submit' action

Wordpress Contact form 7 custom shortcodes

Question :
Contact form 7 has some shortcodes, like [_date] to get todays date. But I want to display the date one week from now.
So I need to create a custom shortcode to Contact form 7 that takes say [next_week] and in the received email the correct date is displayed.
Where and how do I create custom shortcodes to Contact form 7?
Solution code for : Wordpress Contact form 7 custom shortcodes
Adding the following to your functions.php
wpcf7_add_shortcode('custom_date', 'wpcf7_custom_date_shortcode_handler', true);

function wpcf7_custom_date_shortcode_handler($tag) {
    if (!is_array($tag)) return '';

    $name = $tag['name'];
    if (empty($name)) return '';

    $next_week = date('Y-m-d', time() + (60*60*24*7)); 
    $html = '';
    return $html;
}
Now in the "Form" field in CF7 GUI type [custom_date next_week]
Now you can use [next_week] in the message body.