The Future of Web Design: Trends to Watch in 2024

Web design is constantly evolving, influenced by advancements in technology, changes in user behavior, and shifts in aesthetic preferences. As we step into 2024, web designers face exciting challenges and opportunities to create innovative, engaging, and functional websites. From AI-powered design tools to immersive experiences driven by virtual reality (VR) and augmented reality (AR), the future of web design is brimming with potential. In this post, we’ll explore the key trends that will shape web design in 2024 and beyond.

1. AI-Driven Design: Personalization at Scale

Artificial intelligence (AI) is revolutionizing how websites are designed and experienced. In 2024, we expect AI to play an even larger role, from automating design elements to personalizing user experiences.

  • AI-Powered Design Tools: Tools like Figma and Adobe XD are already incorporating AI features that help designers generate layouts, color schemes, and even content suggestions based on user behavior. These tools can analyze past designs and suggest improvements, saving designers time while creating more user-centric designs.
  • Personalization: AI can track user behavior in real-time and tailor website content based on preferences. For example, eCommerce sites can dynamically adjust product recommendations or content based on a user’s browsing history. Websites will become more personalized, reflecting the unique needs and desires of each user, leading to enhanced engagement and satisfaction.

2. Dark Mode as the New Standard

Dark mode has quickly become a favorite of users across the globe, and its adoption in web design continues to rise. In 2024, it’s expected that dark mode will not only be a design choice but a standard feature for most websites.

  • User Preferences: With an increasing number of apps and websites supporting dark mode, users are becoming accustomed to this darker interface. Web designers are now offering users the ability to toggle between light and dark modes, improving accessibility and reducing eye strain in low-light environments.
  • Design Considerations: In 2024, designers will need to ensure that dark mode themes maintain legibility and aesthetic balance. This means carefully choosing contrasting colors and testing for accessibility. Dark mode is no longer just a trend—it’s expected to be built into the core of web design as a user-first feature.

3. Microinteractions: Enhancing User Experience

Microinteractions—small, subtle animations or design changes—are an essential part of modern web design. These interactions help improve the overall user experience (UX) by adding personality, guiding users, and providing feedback on actions.

  • Interactive Animations: In 2024, microinteractions will go beyond simple hover effects. We’re seeing the rise of scroll-triggered animations, loading indicators, and button animations that guide the user journey and add delight to the experience. For example, when a user submits a form, a small animation can confirm the action, offering feedback without interrupting the flow.
  • Personalized Feedback: Microinteractions will also become more personalized. For instance, an eCommerce site might change the color or animation of a product based on user interest or behavior, providing immediate visual feedback to enhance engagement.

4. Immersive Experiences: AR, VR, and 3D Design

Virtual reality (VR) and augmented reality (AR) are no longer just buzzwords; they’re becoming integral components of web design. As technology improves and web browsers support these formats, 2024 will see immersive experiences becoming more mainstream.

  • AR Integration: Augmented reality can bring web design to life, especially for product-based websites. For example, furniture retailers can allow users to visualize how a sofa would look in their living room through an AR interface. Designers will need to ensure that AR experiences are intuitive and accessible, creating an enhanced shopping or browsing experience.
  • VR and 3D Design: With the rise of powerful browsers and VR tools like WebXR, we are likely to see more websites incorporating 3D elements and full-scale VR environments. Whether it's a virtual store tour, interactive 3D products, or immersive gaming experiences, 2024 will demand web designs that can seamlessly integrate these elements for a truly immersive user experience.

5. Responsive Design 2.0: Adaptive to Every Device

Responsive web design has been a cornerstone of web development for years. But in 2024, this concept is evolving into what we might call Responsive Design 2.0, where websites not only adapt to different screen sizes but also intelligently adjust based on user context and environment.

  • Context-Aware Design: Devices are becoming more interconnected, and web designers will need to create sites that respond not just to screen size but to device orientation, location, and user preferences. For example, a website could provide a tailored mobile experience for users who are on the go, while delivering a more detailed desktop version when the user is at home.
  • Voice and Gesture Integration: As voice search and gesture-based navigation gain traction, websites will need to adapt to these new input methods. Web designers in 2024 will focus on creating experiences that work seamlessly with voice assistants and touch gestures, which could reshape how users interact with websites.

6. Accessibility and Inclusivity as Core Principles

The need for inclusive design will continue to grow in 2024. As digital accessibility becomes a key concern globally, web designers will need to ensure their websites are usable by people with diverse abilities, including those with visual, auditory, or mobility impairments.

  • WCAG Compliance: Websites will increasingly need to adhere to the Web Content Accessibility Guidelines (WCAG). In 2024, accessibility will no longer be an afterthought but an integral part of the design process. Designers will focus on features like keyboard navigation, screen reader compatibility, and color contrast to ensure their sites are accessible to everyone.
  • AI-Assisted Accessibility: Tools powered by AI, like automated accessibility checkers, will be incorporated into design tools. These tools will help designers spot accessibility issues early in the design process, ensuring they create websites that meet global accessibility standards.

7. Minimalism and Clean Design

In 2024, minimalism will continue to be a dominant trend in web design. But it’s not about reducing content; it’s about simplifying the user experience while maintaining functionality and beauty. Websites will feature clean layouts, lots of white space, and a focus on core content, all aimed at enhancing clarity and ease of navigation.

  • Focus on Core Content: Rather than overwhelming users with excessive information or design elements, websites will use minimalism to focus users’ attention on what matters. This trend will also promote faster load times, as designers work to reduce unnecessary elements and optimize website performance.
  • Subtle, Elegant Typography: Typography will take center stage in minimalist design. With advancements in web fonts and variable typography, designers will create unique typographic systems that enhance the design without overpowering the content. Typography will play a key role in guiding users through the website, from headings to body text and calls to action.

8. Voice Search Optimization and Conversational UI

As voice assistants like Amazon Alexa, Google Assistant, and Apple Siri become more ubiquitous, voice search optimization will be a critical trend for web designers in 2024. Websites will need to cater to users searching via voice commands, which means adopting more conversational tones in design and content.

  • Conversational User Interfaces (CUI): Websites will start incorporating more chatbots and voice-based interactions to mimic real-life conversations. These conversational UI elements will be integrated into websites, enabling users to interact with the site in a more intuitive way, whether for customer support or product recommendations.

9. Sustainability in Web Design

As awareness of environmental issues grows, sustainability will become an important focus in web design. In 2024, eco-friendly websites will become a priority, with a focus on reducing digital carbon footprints.

  • Energy-Efficient Websites: Designers will seek to build websites that load faster and require fewer resources. By optimizing images, reducing file sizes, and minimizing the number of server requests, websites will use less energy, helping reduce their carbon footprint.
  • Sustainable Hosting: Web hosting services powered by renewable energy will become more popular as businesses look for ways to reduce their environmental impact. Sustainable design will not just be about reducing file sizes but also about supporting green hosting providers.

Conclusion

The future of web design in 2024 is vibrant, exciting, and full of potential. With AI tools, immersive experiences like AR and VR, more focus on accessibility, and an ever-growing need for sustainability, designers have the opportunity to create websites that not only look good but provide exceptional user experiences. By embracing these trends, web designers can stay ahead of the curve, creating sites that are not just functional but transformative.

As these trends take shape, one thing is certain: web design in 2024 will be more dynamic and user-focused than ever before.

Top 10 Time-Saving PHP Snippets for Developers

As developers, saving time without compromising code quality is essential. Below are 10 practical PHP snippets that you can plug and play in your projects to make your development process more efficient.

1. Database Connection (MySQL with PDO)

Effortlessly connect to a MySQL database with this snippet:

try {
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully!";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

2. Form Input Validation

Validate user inputs to prevent invalid data:

function validateInput($input) {
    return htmlspecialchars(strip_tags(trim($input)));
}

// Usage
$name = validateInput($_POST['name'] ?? '');
$email = validateInput($_POST['email'] ?? '');

3. File Upload Handler

Handle file uploads securely with ease:

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
    $uploadDir = 'uploads/';
    $filePath = $uploadDir . basename($_FILES['file']['name']);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
        echo "File uploaded successfully!";
    } else {
        echo "File upload failed.";
    }
}

4. JSON Response Helper

Send JSON responses from your PHP scripts:

function jsonResponse($data, $statusCode = 200) {
    header('Content-Type: application/json');
    http_response_code($statusCode);
    echo json_encode($data);
    exit;
}

// Usage
jsonResponse(['status' => 'success', 'message' => 'Data processed']);

5. Redirect to Another Page

Redirect users to a different URL:

function redirect($url) { header("Location: $url"); exit; } // Usage redirect('https://example.com');

6. Generate Random Strings

Create unique random strings for tokens or IDs:

function generateRandomString($length = 16) {
    return bin2hex(random_bytes($length / 2));
}

// Usage
$token = generateRandomString(32);

7. Pagination Logic

Simplify data pagination:

function paginate($totalItems, $perPage = 10, $currentPage = 1) {
    $totalPages = ceil($totalItems / $perPage);
    $start = ($currentPage - 1) * $perPage;
    return ['start' => $start, 'limit' => $perPage, 'totalPages' => $totalPages];
}

// Usage
$pagination = paginate(100, 10, 2); // Total 100 items, page 2

7. Email Validation

Quickly validate email formats:

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

// Usage
if (isValidEmail('test@example.com')) {
    echo "Valid email!";
} else {
    echo "Invalid email.";
}

9. Prevent SQL Injection

Securely execute prepared statements:

$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => 'user@example.com']);
$user = $stmt->fetch();

10. Sanitize URL Parameters

Prevent malicious data in URLs:

function sanitizeUrlParam($param) {
    return filter_var($param, FILTER_SANITIZE_STRING);
}

// Usage
$id = sanitizeUrlParam($_GET['id'] ?? '');

These snippets are designed to address everyday development challenges, ensuring secure and efficient PHP code.

Which one will you use in your next project? Let me know in the comments below!

For more useful tips and tutorials, check out See Coding!.

AI features into a website built with HTML

Incorporating AI features into a website built with HTML requires a combination of front-end technologies (HTML, CSS, JavaScript) and leveraging AI-powered APIs or services. While HTML itself doesn't directly support AI, it can be used to build the structure and interface for integrating AI tools. Below are some detailed examples of how you can integrate AI features into an HTML-based website:

1. AI-Powered Chatbot (Using JavaScript and APIs)

One of the most common AI features is a chatbot, which can provide support or automate tasks on your website. You can integrate a chatbot using JavaScript and an AI-powered service like Dialogflow, Botpress, or OpenAI's GPT-3.

HTML (structure for chatbot):




    
    
    AI Chatbot
    


    

JavaScript (interaction with AI):

// Function to send messages to the chatbot and get a response
function sendMessage() {
    let userInput = document.getElementById("user-input").value;
    let chatbox = document.getElementById("chatbox");

    // Display user message
    chatbox.innerHTML += `
${userInput}
`; document.getElementById("user-input").value = ''; // Call AI API (here we'll simulate it with a static response) getAIResponse(userInput); } // Simulating an AI response (this would be replaced with a real AI API) function getAIResponse(userInput) { let chatbox = document.getElementById("chatbox"); let response = "I'm here to help!"; // Replace with AI API call chatbox.innerHTML += `
${response}
`; }

CSS (for styling the chatbot interface):

#chatbot-container {
    width: 300px;
    background-color: #f0f0f0;
    border-radius: 8px;
    padding: 20px;
    position: fixed;
    bottom: 20px;
    right: 20px;
}

#chatbox {
    max-height: 200px;
    overflow-y: auto;
    margin-bottom: 10px;
}

#user-input {
    width: 75%;
    padding: 8px;
    margin-right: 10px;
}

button {
    padding: 8px 16px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
}

.user-msg {
    text-align: right;
    background-color: #e0e0e0;
    padding: 8px;
    margin-bottom: 8px;
    border-radius: 5px;
}

.ai-msg {
    text-align: left;
    background-color: #d1e7ff;
    padding: 8px;
    margin-bottom: 8px;
    border-radius: 5px;
}

In this example, a simple chatbot UI is created using HTML. The chatbot processes the user's input using JavaScript. In a real scenario, you would replace the getAIResponse() function with an actual AI API call (e.g., Dialogflow or GPT-3) to generate responses dynamically.

2. AI-Powered Content Personalization

AI can personalize content for users based on their behavior, location, or preferences. For this, you would integrate an AI-based recommendation system (e.g., TensorFlow.js, OpenAI, or Recommender APIs) using JavaScript.

For example, a personalized greeting message:




    
    
    AI Personalization


    

Welcome to Our Website

In this example, JavaScript simulates personalization by displaying a welcome message based on user data. In a real-world scenario, this could be powered by an AI algorithm analyzing user activity, interests, or past behavior.

3. AI-Powered Search Engine (Using Algolia or Elasticsearch)

AI can enhance the search functionality by analyzing and understanding user queries. You can integrate services like Algolia or Elasticsearch to provide more relevant and personalized search results.

Here’s an example of how you might use Algolia to power a search bar:




    
    
    AI Search Engine
    


    
    

In this example, Algolia is used to power a search bar. It automatically suggests results based on user input. You can use AI-driven algorithms like AI-powered query understanding to provide better search results.

While HTML is essential for structuring the content and user interface of a website, AI features often require integrating JavaScript, external APIs, or libraries like TensorFlow.js, Dialogflow, or Algolia. By combining AI technologies with HTML, you can enhance the interactivity, personalization, and overall user experience on your website.

WooCommerce Support in a Child Theme: A Complete Guide

When working with WordPress, using a child theme ensures that your customizations remain intact even after a theme update. If you are using WooCommerce, adding support for it in a child theme is a must to safely customize templates or modify functionality without breaking the core theme or plugin features.

This guide will walk you through the process of integrating WooCommerce support into a child theme.

Why Use a Child Theme for WooCommerce?

  1. Preserve Customizations: Direct modifications to the parent theme get overwritten during updates, but child themes keep your changes safe.
  2. Safe Experimentation: A child theme lets you experiment with WooCommerce features without affecting the live site.
  3. Enhanced Flexibility: Modify WooCommerce templates or add hooks and filters specific to your requirements.

Steps to Add WooCommerce Support in a Child Theme

1. Create a Child Theme

If you haven’t already created a child theme, follow these steps:

  • Create a folder for your child theme in /wp-content/themes/, for example, your-theme-child/.
  • Add a style.css file with the following header:
/*
 Theme Name:   Your Theme Child
 Template:     your-theme
 Text Domain:  your-theme-child
*/
  • Create a functions.php file to enqueue styles and functions:
function your_theme_child_enqueue_styles() {
    wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
}
add_action('wp_enqueue_scripts', 'your_theme_child_enqueue_styles');

2. Add WooCommerce Support

To ensure compatibility with WooCommerce, add the following code to your child theme’s functions.php:

// Add WooCommerce support
function your_theme_child_add_woocommerce_support() {
    add_theme_support('woocommerce');
}
add_action('after_setup_theme', 'your_theme_child_add_woocommerce_support');

This code notifies WooCommerce that your theme supports its features.

3. Customize WooCommerce Templates

WooCommerce templates are located in the woocommerce/templates/ directory of the plugin. To override these templates:

If you want to add custom styles for WooCommerce, enqueue them in functions.php:

  • Copy the template file you want to customize (e.g., cart.php, single-product.php) from /wp-content/plugins/woocommerce/templates/ to your child theme in a woocommerce/ folder.
/wp-content/themes/your-theme-child/woocommerce/cart/cart.php

4. Enqueue WooCommerce-Specific Styles

If you want to add custom styles for WooCommerce, enqueue them in functions.php:

function your_theme_child_enqueue_woocommerce_styles() {
    if (class_exists('WooCommerce')) {
        wp_enqueue_style('child-woocommerce-style', get_stylesheet_directory_uri() . '/woocommerce.css');
    }
}
add_action('wp_enqueue_scripts', 'your_theme_child_enqueue_woocommerce_styles');

Now, create a woocommerce.css file in your child theme directory and add your styles.

5. Leverage WooCommerce Hooks

WooCommerce provides various hooks to customize functionality. For example, to add a custom message on the product page:

add_action('woocommerce_single_product_summary', 'custom_product_message', 25);
function custom_product_message() {
    echo '

Thank you for shopping with us!

'; }

Happy coding!

For more practical tutorials and tips, explore other posts on See Coding.

How to Build a Social Media Cost Calculator with HTML, CSS, and JavaScript

Here's a sample blog post about building a Social Media Cost Calculator using HTML, CSS, and JavaScript:

How to Build a Social Media Cost Calculator with HTML, CSS, and JavaScript

If you're managing social media campaigns, you know how important it is to estimate costs effectively. Today, we'll create a simple Social Media Cost Calculator using HTML, CSS, and JavaScript. This tool will help you or your clients calculate ad spend, content creation costs, and management fees—all in real-time!

Why Build a Social Media Cost Calculator?

Whether you're a digital marketer or a business owner, a cost calculator:

  • Saves time in budgeting.
  • Provides clear insights into campaign expenses.
  • Simplifies communication with clients or stakeholders.

Features of the Calculator

  • Ad Spend Input: Budget allocated for ads on platforms like Facebook or Instagram.
  • Content Creation Input: Cost for creating graphics, videos, or blog posts.
  • Management Fees Input: Payment for social media account management.
  • Real-Time Cost Calculation: Instantly calculates the total.

Step 1: HTML Structure

The HTML defines the layout of our calculator. Here's the code:




  
  
  Social Media Cost Calculator


  

Social Media Cost Calculator

Total Cost: ₹0

Step 2: Styling with CSS

Add a clean, responsive design using CSS:

body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f9;
  margin: 0;
  padding: 20px;
}

.calculator {
  max-width: 400px;
  margin: auto;
  background: #ffffff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  font-size: 24px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  font-size: 16px;
  color: #555;
  margin-bottom: 5px;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  border: none;
  color: white;
  font-size: 16px;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.result {
  margin-top: 20px;
  font-size: 18px;
  color: #333;
  text-align: center;
}

Step 3: Adding JavaScript

Implement logic to calculate the total cost dynamically:

document.getElementById("calculateBtn").addEventListener("click", function () {
  const adSpend = parseFloat(document.getElementById("adSpend").value) || 0;
  const contentCreation = parseFloat(document.getElementById("contentCreation").value) || 0;
  const managementFees = parseFloat(document.getElementById("managementFees").value) || 0;

  const totalCost = adSpend + contentCreation + managementFees;

  document.getElementById("totalCost").textContent = `Total Cost: ₹${totalCost.toFixed(2)}`;
});

Testing the Calculator

  1. Copy and paste the code into three files: index.html, styles.css, and script.js.
  2. Open index.html in your browser.
  3. Enter different values to see the total cost update instantly.

Include navigation (arrows) and pagination (dots) on each slide itself in a slick slider

If you want to include navigation (arrows) and pagination (dots) on each slide itself in a slick slider, here's how you can achieve this:

1. HTML Structure

You need to place arrows and dots inside each slide so that they appear uniquely for each one.

Slide 1

Slide 2

Slide 3

2. Initialize Slick

Use Slick’s API to manage navigation and pagination for each slide:

$(document).ready(function () {
  $('.slider').slick({
    slidesToShow: 1,
    slidesToScroll: 1,
    infinite: true,
    speed: 500,
    arrows: false, // Disable global arrows
    dots: false, // Disable global dots
  });

  // Add custom controls for each slide
  $('.slider .slide').each(function (index, slide) {
    const $prevButton = $(slide).find('.prev');
    const $nextButton = $(slide).find('.next');

    // Go to the previous slide on click
    $prevButton.on('click', function () {
      $('.slider').slick('slickPrev');
    });

    // Go to the next slide on click
    $nextButton.on('click', function () {
      $('.slider').slick('slickNext');
    });

    // Generate custom dots for this slide
    const $dotsContainer = $(slide).find('.dots');
    const slideCount = $('.slider .slide').length;

    for (let i = 0; i < slideCount; i++) {
      const dot = $(``);
      dot.on('click', function () {
        $('.slider').slick('slickGoTo', $(this).data('slide'));
      });
      $dotsContainer.append(dot);
    }
  });

  // Sync active dots with slick events
  $('.slider').on('afterChange', function (event, slick, currentSlide) {
    $('.custom-dot').removeClass('active');
    $(`.custom-dot[data-slide="${currentSlide}"]`).addClass('active');
  });
});

3. CSS Styling

Make it visually appealing with CSS:

.slider {
  position: relative;
}

.slide {
  text-align: center;
  position: relative;
}

.controls {
  position: absolute;
  bottom: 20px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.controls .prev,
.controls .next {
  background-color: #007bff;
  color: #fff;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.controls .prev:hover,
.controls .next:hover {
  background-color: #0056b3;
}

.controls .dots {
  display: flex;
  gap: 5px;
}

.controls .custom-dot {
  background-color: #ddd;
  border: none;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  cursor: pointer;
}

.controls .custom-dot.active {
  background-color: #007bff;
}

4. Final Outcome

  • Each slide now has its own arrows and pagination dots.
  • Clicking on these controls interacts seamlessly with the slick slider.
  • Dots update dynamically to reflect the current active slide.

Using jQuery, we can easily hide and restore the placeholder when the user clicks on the field

you can use jQuery to hide the placeholder when a user focuses on a field and restore it when they blur (leave) the field. Here's an example:

Input field HTML: 

jQuery Code:

$(document).ready(function () {
	const $input = $('#nameField');

	$input.on('focus', function () {
		$(this).data('placeholder', $(this).attr('placeholder')); // Save placeholder
		$(this).attr('placeholder', ''); // Remove placeholder
	});

	$input.on('blur', function () {
		$(this).attr('placeholder', $(this).data('placeholder')); // Restore placeholder
	});
});

Explanation

Focus Event:

  • Triggered when the input field is clicked or gains focus.
  • Save the current placeholder value in a custom data attribute (data('placeholder')) and clear the placeholder.

Blur Event:

  • Triggered when the input field loses focus.
  • Restore the placeholder from the saved data attribute.

Retrieve coupon details from coupon code WooCommerce

In order for the WC_Coupon function to work, I needed to add the "new" keyword prior to calling the function. As demonstrated below.
$coupon_code = 'save10percent';
global $woocommerce;
$c = new WC_Coupon($coupon_code);
Now I can get details about the coupon like so
 echo "Discount Amount ".$c->amount;//Get Discount amount
echo "Discount Type ".$c->discount_type;//Get type of discount
echo "Individual Use ".$c->individual_use;//Get individual use status
echo "Usage Count ".$c->usage_count;//Get number of times the coupon has been used
echo "Uage Limit ".$c->usage_limit;//Get usage limit
echo "Coupon Description ".$c->description;//Get coupon description

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;