How to check whether user has paid for a product already in WooCommerce?

This is sort of unique equation i had to develop, here i need to find out whether user has paid for the product or not, if already paid then show the premium content, if not then ask for payment. To achieve that i had to develop a function which can return me whether user has paid or not. Here is the function for your future use:

function CheckWhetherUserPaid() {

$bought = false;

// Set HERE ine the array your specific target product IDs
$prod_arr = array( ’21’, ’67’ );

// Get all customer orders
$customer_orders = get_posts( array(
‘numberposts’ => -1,
‘meta_key’ => ‘_customer_user’,
‘meta_value’ => get_current_user_id(),
‘post_type’ => ‘shop_order’, // WC orders post type
‘post_status’ => ‘wc-completed’ // Only orders with status “completed”
) );
foreach ( $customer_orders as $customer_order ) {
// Updated compatibility with WooCommerce 3+
$order_id = method_exists( $order, ‘get_id’ ) ? $order->get_id() : $order->id;
$order = wc_get_order( $customer_order );

// Iterating through each current customer products bought in the order
foreach ($order->get_items() as $item) {
// WC 3+ compatibility
if ( version_compare( WC_VERSION, ‘3.0’, ‘<' ) ) { $product_id = $item['product_id']; } else { $product_id = $item->get_product_id();
// Your condition related to your 2 specific products Ids
if ( in_array( $product_id, $prod_arr ) ) {
$bought = true;
// return “true” if one the specifics products have been bought before by customer
return $bought;

How to check active subscriptions using YITH WooCommerce?

Recently while working over a membership site, i came up with a problem: “How to check active subscriptions using YITH WooCommerce plugin”? I search through the entire internet but couldn’t locate a good resource to solve this issue. Then i went and tried to look for any table in the database, but yet nothing exist in it either. So in short, YITH doesn’t use any additional table, it just uses the inbuilt tables i.e posts, meta posts etc.

Here is the snippet of code which can help you achieve this:

function CheckSubscriptionByEmail($email) {

// getting all the records of the user by email for the subscription
$subscriptions = get_posts( array(
‘numberposts’ => -1,
‘post_type’ => ‘ywsbs_subscription’, // Subscription post type
‘orderby’ => ‘post_date’, // ordered by date
‘order’ => ‘ASC’,
‘meta_query’ => array(
‘key’ => ‘_billing_email’, //additional fields being used to get the data
‘value’ => $email,
‘compare’ => ‘=’
‘key’ => ‘_status’,
‘value’ => ‘active’, //active subscriptions
‘compare’ => ‘=’
) );

// check if user has any active subscription
foreach ( $subscriptions as $post ) : setup_postdata( $post );
$nextdue = get_post_meta(get_the_id(), ‘_payment_due_date’,true);
$current_date = date(“Y-m-d”);
$date_to_compare = date(“Y-m-d”,strtotime($nextdue));
if (strtotime($date_to_compare) > strtotime($current_date)) {
echo “active”; //returns active


Some of the references that may help you in understanding this code:
How WP_Meta_Query functions?

Other related WooCommerce Problems:
How to Make your WooCommerce Shopping Cart Responsive?
Growth Hacking Techniques for your eCommerce Project

How to get image gallery in Woocommerce?

Recently came through a problem, where i had to build a custom single page for the Products. The requirement was to use the featured image as a the main image while the gallery images needed to be placed at the bottom.

Getting the featured image for a WooCommerce product is fairly simple, it works very similar to how you get an image for a post. You can also reference: How to get featured images outside loop in WordPress?

For Woocommerce Gallery, here is the snippet of code that can help:

$product_id = ’14’; // id of the product, you can also use get_the_id() for this within the single page
$product = new WC_product($product_id);
$attachment_ids = $product->get_gallery_attachment_ids();
foreach( $attachment_ids as $attachment_id )
// Display the image URL
echo $Original_image_url = wp_get_attachment_url( $attachment_id );

// Display Image instead of URL
echo wp_get_attachment_image($attachment_id, ‘full’);


How to track the most viewed post in WordPress using code?

1. Add the following piece of snippet in your function.php file, the code will help detect post views count and store it as a custom field for each post:

function set_post_views($postID) {
$count_key = ‘post_views_count’;
$count = get_post_meta($postID, $count_key, true);
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, ‘0’);
update_post_meta($postID, $count_key, $count);

remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0);

2. Now to track no of times the post was viewed, lets place this snippet at the end of the function.php file:

function track_post_views ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
add_action( ‘wp_head’, ‘track_post_views’)

Now every time a visitor visit your post, the custom field will be updated.

3. To display the no of views for a post, add the following snippet of code in function.php file:

function get_post_views($postID){
$count_key = ‘post_views_count’;
$count = get_post_meta($postID, $count_key, true);
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, ‘0’);
return “0 View”;
return $count.’ Views’;

Now where ever you want to display the post views for a specific post, just send the id as the parameter and it will fetch the no of views.


How to easily export and import WordPress Sites?

Recently, i ran into issue of WordPress site not getting properly deployed. My normal method of deployment of the site was:

a. Backup the files
b. Backup the database file
c. Goto the CPanel deploy the files
d. Change few settings in database sql file for the urls
e. Create database on to the new server and deploy the database file

This method use to work almost all the time for me, i would rate it 100%, but not until today, where i will place a minus 1 to this formla and call it 99% of the time the above method works. Here is the new way.

I came across a plugin from servmask called as “All in One WP Migration plugin”. This is a perfect and time saving solution and best part, its FREE plugin. This plugin exports your WordPress website including the database, media files, plugins and themes with no technical knowledge required. Upload your site to a different location with a drag and drop in to WordPress. Watch the video below to fully understand the process:

The plugin does not have any dependancies, making it compatible with all PHP hosting providers. We support a vast range of hosting providers. Some of the most popular include: Bluehost, InMotion, Web Hosting Hub, Siteground, Pagely, Dreamhost, Justhost, GoDaddy, WP Engine, Site5, 1&1, Pantheon.


If you feel, this plugin could be helpful to your friend, share with them as “Sharing is Caring”.

How to send data via AJAX from frontend to backend in WordPress Plugin?

Recently, i went into a problem where i had to create a form from the backend plugin without touching the theme and then pass that form data back to the plugin further processing. Here is how this can be achieved:

/* Firstly Add this code to your plugin and load the script file together with the AJAX URL */

function ajax_load_scripts() {
wp_enqueue_script( “ajax-test”, plugin_dir_url( __FILE__ ).’js/script.js’, array( ‘jquery’ ) );
wp_localize_script( ‘ajax-test’, ‘the_ajax_script’, array(‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ) ) );
add_action(‘wp_ajax_test_response’, ‘ajax_load_scripts’);

Now open the script file and add the follow code:

function sendData() {
var data = {
action: ‘test_response’,
post_var: ‘response code to return’
};, data, function(response) {

In the plugin, add the following code to handle the response:

function ajax_process_request() {
if ( isset( $_POST[“post_var”] ) ) {
echo $_POST[“post_var”];
add_action(‘wp_ajax_test_response’, ‘ajax_process_request’);

At the front end, you can have a form where you should send the data via jQuery using AJAX with the code mentioned above i.e sendData().

Hope this piece of snippet will help you handle the AJAX request over WordPress Plugin.

How to get an Array onto your email in WordPress?

Here is the simple snippet of code that can help you achieve this:

$headerstext = array(‘Content-Type: text/html; charset=UTF-8’); // just for getting it as html email
$message = “Coupon List: ” . print_r( $yourarray, true ); //replace $yourarray with your array
wp_mail(‘[email protected]’, ‘Coupon List’, $message,$headerstext); //replace email with yours

Note: Do check your SPAM folder.

How to disable Yoast SEO Plugin for a specific page?

I run into a problem, where i had to make Yoast SEO plugin off/disable for a page since i wanted to handle this SEO meta titles and description automatically via some piece of code. Here is the code which can help you achieve this:


function remove_wpseo(){
if (is_page(‘pagename’)) { /* pagenmae could be your slug of page, just replace it */
global $wpseo_front;
else {
$wp_thing = WPSEO_Frontend::get_instance();

Note: Place above code at the end of the functions.php file in your WordPress Theme.

How to get featured images outside loop in WordPress?

This is a very common requirement that we need to display the post image. The way to do this outside the loop is to use the following snippet:

$post_id = 123; // use your post id
$thumb_id = get_post_thumbnail_id($post_id);
$thumb_url_array = wp_get_attachment_image_src($thumb_id, ‘full’, true);
$thumb_url = $thumb_url_array[0]; //this gets you the url of the image

Within the loop its simple, just modify the above code a bit and use:

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

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

$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, ‘full’, true);
$thumb_url = $thumb_url_array[0]; //this gets you the url of the image

endwhile; else: ?>

<p>Sorry, no posts to list</p>

<?php endif; ?>

ScrollTo Div using jQuery over a WordPress Theme

This is one of the very common requirements that you want your link to scroll at the bottom section using animation. Here is the code which can help you achieve this:

Assuming you have a button with the id button, try this example:

function scrollTo(divname) {
jQuery(‘html, body’).animate({
scrollTop: jQuery(“#”+divname).offset().top
}, 2000);

Note: You can adjust the speed changing 2000 to what ever number you like, the more the value the more slow it will scroll.

How to subscribe user details using mailchimp API?

Recently a problem came in, where i had to send the details to mailchimp. I didn’t want to use bulk of the code provided via the libraries as my major aim of the problem was to just send the email and a bit of additional data.

To solve this, here is the piece of the code:

$data = [
’email’ => ‘[email protected]’,
‘status’ => ‘subscribed’,
‘firstname’ => ‘John Doe’,
‘answers’ => ‘Answer List Here, You can change this field’,


function syncMailchimp($data) {
$apiKey = ‘YOUR API KEY’;
$listId = ‘YOUR LIST ID’;

$memberId = md5(strtolower($data[’email’]));
$dataCenter = substr($apiKey,strpos($apiKey,’-‘)+1);
$url = ‘https://’ . $dataCenter . ‘’ . $listId . ‘/members/’ . $memberId;

$json = json_encode([
’email_address’ => $data[’email’],
‘status’ => $data[‘status’], // “subscribed”,”unsubscribed”,”cleaned”,”pending”
‘merge_fields’ => [
‘FNAME’ => $data[‘firstname’],
‘ANSWERS’ => $data[‘answers’]

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_USERPWD, ‘user:’ . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, [‘Content-Type: application/json’]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, ‘PUT’);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

Reference Docs: