How to Create a Custom HubSpot Contact Form with API Integration

Introduction:
HubSpot is a powerful CRM platform that allows businesses to manage their contacts efficiently. In this tutorial, we will create a simple custom contact form using PHP that integrates with HubSpot’s API to store user data directly into your HubSpot CRM.

Why Use a Custom Contact Form?
A custom contact form offers more flexibility than standard HubSpot forms. You can customize the design, add validations, and integrate with other tools as needed.

Steps to Create a Custom HubSpot Contact Form

1. Get Your HubSpot API Key

To connect to HubSpot's API, you need an API key. You can find it by navigating to:

  • HubSpot Dashboard → Settings → Integrations → API Key

Copy and keep this key safe as we will use it in our code.

2. Create the PHP Form

Below is the PHP code for the custom HubSpot contact form:

  
  
// Define HubSpot API Key
$hubspot_api_key = 'YOUR_HUBSPOT_API_KEY';

// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $contact_data = [
        'fields' => [
            ['name' => 'firstname', 'value' => $_POST['firstname']],
            ['name' => 'lastname', 'value' => $_POST['lastname']],
            ['name' => 'email', 'value' => $_POST['email']]
        ]
    ];
    
    $endpoint = "https://api.hubapi.com/crm/v3/objects/contacts?hapikey=$hubspot_api_key";
    
    $ch = curl_init($endpoint);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($contact_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    echo "Contact submitted successfully!";
}

3. Create the HTML Form

Add this HTML code to your project to create a user-friendly form:




    
    
    HubSpot Contact Form


    

HubSpot Contact Form




4. Deploy and Test the Form

  • Save the PHP file and host it on your web server.
  • Open the form in your browser, enter details, and submit.
  • The submitted contact details should now appear in your HubSpot CRM.
Creating a custom HubSpot contact form using API integration allows for more flexibility in capturing user data. You can further enhance this by adding custom fields, validation, and error handling. Try implementing this on your website and streamline your lead management with HubSpot CRM.

Introduction to HubSpot Development: A Beginner’s Guide

HubSpot is a powerful platform that offers marketing, sales, customer service, and content management solutions. Developers can extend and customize its functionality through HubSpot’s API, CMS Hub, and custom modules. If you're new to HubSpot development, this guide will help you get started.

Why Develop on HubSpot?

  1. User-Friendly CMS - HubSpot’s CMS is designed for marketers but offers flexibility for developers to create custom themes and modules.
  2. Extensive API Support - HubSpot provides REST APIs for CRM, marketing automation, and more, allowing integration with third-party services.
  3. HubL Templating Language - HubSpot uses HubL, a proprietary templating language, to create dynamic pages and emails.
  4. Built-in Security & Performance - The platform handles hosting, security, and performance optimization, reducing the need for external configurations.

Getting Started with HubSpot Development

1. Setting Up a Developer Account

To start developing on HubSpot, you need a free developer account. Sign up at HubSpot Developer Portal.

2. Understanding HubSpot CMS

HubSpot’s CMS allows you to create themes, templates, and modules using HubL, HTML, CSS, and JavaScript.

  • Themes: Collections of templates and assets to define the site's design.
  • Modules: Reusable UI components for adding functionality.
  • Templates: Define page layouts and content structure.

3. Using HubSpot CLI

HubSpot’s CMS allows you to create themes, templates, and modules using HubL, HTML, CSS, and JavaScript.HubSpot offers a Command Line Interface (CLI) for local development. Install it using:

  
npm install -g @hubspot/cli

With this, you can develop themes, modules, and templates locally and sync them with your HubSpot account.

4. Working with HubL (HubSpot Markup Language)

HubL is HubSpot’s templating language, used for dynamic content. Example of a simple loop:

  
{% for post in blog_posts %}
   

{{ post.title }}

{% endfor %}

5. Exploring HubSpot API

HubSpot provides a range of APIs for automation and integration:

  • CRM API - Manage contacts, companies, and deals.
  • Forms API - Handle form submissions programmatically.
  • Marketing API - Automate emails, social posts, and campaigns.
  • Tickets API - Manage customer support tickets.

Example API call using JavaScript:

  
fetch('https://api.hubapi.com/crm/v3/objects/contacts', {
   headers: { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' }
})
.then(response => response.json())
.then(data => console.log(data));

HubSpot development provides a wide range of tools for customizing websites, automating tasks, and integrating with external services. Whether you're a beginner or an advanced developer, mastering HubL, API integrations, and HubSpot’s CMS will help you create powerful solutions.

If you’re looking for more tutorials, stay tuned to our blog for advanced HubSpot development tips!

How to Use Elementor Forms in Your Custom Template

Elementor is a powerful page builder that simplifies WordPress design, but sometimes you may want to use an Elementor Form inside a custom template. Whether you're building a custom theme or creating a special layout, integrating an Elementor Form is straightforward. In this post, I'll walk you through three simple methods to achieve this.

Method 1: Using Elementor Shortcode

The easiest way to insert an Elementor form into a custom template is by using the Elementor template shortcode.

Steps:

  1. Create Your Form – Design your form using the Elementor Form widget and save it as a template.
  2. Get the Template Shortcode – Navigate to Templates > Saved Templates in WordPress and copy the shortcode of the saved template.
  3. Embed the Shortcode in Your Custom Template – Paste the shortcode into your custom template file using the following PHP function
  
echo do_shortcode('[elementor-template id="YOUR_TEMPLATE_ID"]');

Replace

YOUR_TEMPLATE_ID
with the actual ID of your saved template.

Method 2: Using Elementor's PHP Function

For better control over the output, you can use Elementor's built-in function to render a template inside your PHP file.

Steps:

  1. Ensure your form is saved as a template in Elementor.
  2. Insert the following PHP code in your custom template file:
  
echo \Elementor\Plugin::instance()->frontend->get_builder_content(YOUR_TEMPLATE_ID);

his function retrieves and displays the content of the specified Elementor template.

Method 3: Using Elementor’s API for Dynamic Embedding

If you need more flexibility, you can use Elementor’s API to dynamically fetch and display the form template.

Steps:

  1. Ensure Elementor is active on your site.
  2. Add this code to your custom template file:
  
use Elementor\Plugin;

$elementor = Plugin::instance();
echo $elementor->frontend->get_builder_content_for_display(YOUR_TEMPLATE_ID);

This method allows for more dynamic form rendering.

Final Thoughts

Using Elementor Forms in a custom template can enhance your website’s functionality without relying on additional plugins. Whether you prefer using a shortcode, PHP functions, or Elementor's API, these methods provide a seamless way to integrate forms into your custom layouts.

Do you use Elementor Forms in your custom templates? Let me know in the comments!

How to Limit Navigation Dots in Slick Slider Using jQuery

Slick Slider is a popular jQuery plugin for creating responsive carousels. However, when working with large numbers of slides, the default dot navigation can become overwhelming. In this tutorial, we will learn how to limit the number of visible dots in Slick Slider using jQuery.

Why Limit Navigation Dots?

By default, Slick Slider generates one dot for each slide. If your slider has 20+ slides, it results in a cluttered navigation UI. Limiting the dots to a fixed number (e.g., 6 dots at a time) ensures a clean and user-friendly interface.

Implementing Slick Slider with Limited Dots

Step 1: Include Required Files

First, make sure to include jQuery and Slick Slider in your project.

  







Step 2: Create the Slider Markup

 

Step 3: Initialize Slick Slider and Limit Dots

 
jQuery(document).ready(function($) {
    var maxDots = 6; // Limit the visible dots to 6

    $('.brand_list_slider').slick({
        dots: true,
        infinite: true,
        speed: 500,
        slidesToShow: 1,
        slidesToScroll: 1,
        centerMode: true,
        centerPadding: '80px',
    });

    $('.brand_list_slider').on('init', function(event, slick) {
        setTimeout(function() { limitDots($('.brand_list_slider'), maxDots, slick); }, 100);
    });

    $('.brand_list_slider').on('beforeChange', function(event, slick, currentSlide, nextSlide) {
        limitDots($('.brand_list_slider'), maxDots, slick, nextSlide);
    });

    function limitDots(slider, maxDots, slick, currentIndex = 0) {
        var dots = slider.find('.slick-dots li');
        var totalDots = dots.length;

        if (totalDots > maxDots) {
            dots.hide(); // Hide all dots

            var start = Math.max(0, Math.min(totalDots - maxDots, currentIndex - Math.floor(maxDots / 2)));
            var end = start + maxDots;

            dots.slice(start, end).show(); // Show only a limited set of dots
        }
    }
});

Step 4: Custom CSS for Dot Navigation

 
.slick-dots {
    display: flex !important;
    justify-content: center;
    overflow: hidden;
}
.slick-dots li {
    display: none; /* Hide all dots initially */
}
.slick-dots li button {
    font-size: 14px;
}

How It Works

  • Slick Slider Initialization – We initialize the slider with navigation dots enabled.
  • limitDots()** Function** – It hides all dots initially and then displays only 6 at a time.
  • Event Handling – The function runs on init and beforeChange to update the dots dynamically as the slides change.

Conclusion

By implementing this approach, you can enhance the usability and appearance of Slick Slider’s navigation. This method is especially useful for sliders with many slides, keeping the navigation clean and intuitive.

Try it out in your next project and let us know your thoughts in the comments!

Building Complex Repeaters with ACF and Custom Code

Advanced Custom Fields (ACF) is a WordPress powerhouse for creating dynamic, customizable sites. But when it comes to managing complex repeaters with nested fields, things can get a little tricky. In this guide, we’ll walk through how to leverage ACF and custom code to build and display intricate repeaters seamlessly

What Are Repeaters in ACF?

The ACF Repeater Field allows you to create rows of data that you can repeat as needed. Each row can contain subfields such as text, images, or even other repeaters. This makes it ideal for:

  • Multi-level FAQs
  • Team member directories
  • Portfolio projects with multiple attributes

Setting Up Your Repeater Field

  1. Install and Activate ACF Pro:
    Repeaters are a Pro feature, so make sure you’re using the correct version.
  2. Create a New Field Group:
    • Go to ACF → Field Groups.
    • Add a Repeater field.
    • Configure subfields such as title, description, or even nested repeaters.
  3. Assign the Field Group:
    Attach your field group to the desired post, page, or custom post type.

Customizing with PHP

To display your repeater data on the front end, you’ll need some custom PHP code. Let’s say we’re working with a Portfolio repeater that has a nested Project Details repeater.

 
' . esc_html($portfolio_title) . '';  
        echo '

' . esc_html($portfolio_description) . '

'; if (have_rows('project_details')): echo '
    '; while (have_rows('project_details')): the_row(); $project_name = get_sub_field('project_name'); $project_status = get_sub_field('status'); echo '
  • ' . esc_html($project_name) . ' - ' . esc_html($project_status) . '
  • '; endwhile; echo '
'; endif; endwhile; endif; ?>

Styling Your Repeaters

Use CSS to create a clean, visually appealing structure. For example:

 
.portfolio-title {
  font-size: 24px;
  font-weight: bold;
  margin-top: 20px;
}

.project-details ul {
  list-style-type: disc;
  padding-left: 20px;
}

.project-details li {
  margin-bottom: 5px;
}

Tips for Optimization

  • Use Caching: For large datasets, implement caching to reduce database queries.
  • Lazy Loading: If your repeater includes images, load them lazily for better performance.
  • Conditional Logic: Only load repeaters when necessary to improve speed.

Conclusion

By combining ACF’s repeater fields with custom PHP and styling, you can build powerful, dynamic content structures. Whether you're crafting nested FAQs or detailed portfolios, the possibilities are endless with a little creativity and coding know-how.

Have you worked with complex repeaters before? Share your tips in the comments below!

Displaying ACF Fields in WordPress Templates

Advanced Custom Fields (ACF) is a powerful plugin that enables WordPress developers to add custom fields to posts, pages, and custom post types. By leveraging ACF, you can create highly customized WordPress websites with dynamic content tailored to your needs.

In this guide, we'll walk you through how to display ACF fields in your WordPress templates. Whether you're creating a custom theme or modifying an existing one, this step-by-step tutorial will help you integrate ACF seamlessly

Step 1: Install and Set Up ACF

If you haven’t already, install and activate the ACF plugin. Once installed:

  1. Go to Custom Fields in the WordPress admin menu.
  2. Click Add New to create a field group.
  3. Add your desired custom fields (e.g., text, number, dropdown, etc.).
  4. Assign the field group to specific post types or pages where you want these fields to appear.

For example, let’s create a field group with a dropdown field called "Property Type" for a real estate website.

Step 2: Retrieve ACF Fields in Templates

After setting up your custom fields, you can display their values in your WordPress theme templates using PHP. Here's how:

1. Basic Usage

Basic Usage
Use the get_field() function to retrieve field values in your templates. For example:

 


Replace 'field_name' with the actual name of your custom field.

2. Displaying Image Fields

If your custom field is an image, you can display it like this:

 
';
}
?>

3. Repeater Fields

For repeater fields, use a loop:

 

    

4. Flexible Content Fields

For flexible content fields, handle layouts conditionally:

 

    
        
            

Step 3: Debugging ACF Fields

If the field is not displaying as expected:

  • Ensure the field is correctly assigned to the post, page, or template.
  • Double-check the field name in the template.
  • Use var_dump(get_field('field_name')); to debug the field's value.

Step 4: Best Practices

  1. Sanitize Output
    Always sanitize dynamic content to prevent security vulnerabilities. Use esc_html(), esc_url(), and other WordPress sanitization functions where appropriate.

  2. Use Conditional Statements
    Wrap your get_field() calls with conditional statements to prevent errors when fields are empty.

  3. Leverage Template Parts
    For modular and maintainable code, consider creating template parts for displaying ACF fields.

Conclusion

By following these steps, you can harness the full potential of ACF to create dynamic, user-friendly WordPress sites. Whether you're building a portfolio, an e-commerce site, or a blog, ACF adds flexibility to your development process.

Have you tried using ACF in your projects? Share your thoughts and experiences in the comments below!

How to Use ACF with WP Query for Advanced Filtering

Advanced Custom Fields (ACF) is one of the most powerful tools for adding custom data to WordPress. When combined with WP_Query, you can create advanced filtering systems to display dynamic content based on custom field values. In this guide, we’ll explore how to use ACF with WP_Query for advanced filtering in WordPress.

Step 1: Install and Set Up ACF

If you haven’t already, install and activate the ACF plugin. Once installed:

  1. Go to Custom Fields in the WordPress admin menu.
  2. Click Add New to create a field group.
  3. Add your desired custom fields (e.g., text, number, dropdown, etc.).
  4. Assign the field group to specific post types or pages where you want these fields to appear.

For example, let’s create a field group with a dropdown field called "Property Type" for a real estate website.

Step 2: Add Custom Fields to Your Posts

After setting up your fields, navigate to the posts or custom post types where the fields are assigned. Populate these fields with relevant data for filtering.

Example: Add "Apartment," "Villa," or "Studio" under the "Property Type" field for different posts.

Step 3: Write a Custom WP_Query with ACF Filters

To filter posts based on ACF fields, you’ll use the `meta_query` parameter in WP_Query. Here’s an example code snippet:

 
 'property', // Replace with your post type
    'meta_query' => [
        [
            'key' => 'property_type', // ACF field key
            'value' => 'Apartment',   // Value to match
            'compare' => '=',        // Comparison operator
        ],
    ],
    'posts_per_page' => 10, // Limit the number of results
];

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // Output your post content here
        echo '

' . get_the_title() . '

'; } wp_reset_postdata(); } else { echo 'No results found.'; } ?>

In this example, we’re querying posts from the "property" post type where the "Property Type" field is set to "Apartment."

Step 4: Allow Dynamic Filtering with a Form

To let users dynamically filter results, you can create a front-end form. Here’s an example:

 
'property', 'meta_query' => $selected_type ? [ [ 'key' => 'property_type', 'value' => $selected_type, 'compare' => '=', ], ] : [], 'posts_per_page' => 10, ]; $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); echo '

' . get_the_title() . '

'; } wp_reset_postdata(); } else { echo 'No results found.'; } ?>

This form allows users to select a property type, and the query dynamically adjusts based on their selection.

Step 5: Optimize the Query for Performance

For large datasets, consider the following optimizations:

  1. Index your database: Ensure that custom fields are indexed in the database to speed up meta queries.
  2. Use Transients: Cache query results using WordPress transients for frequently accessed data.
  3. Pagination: Add pagination to handle large numbers of results efficiently.

Example pagination code:

 
$big = 999999999; // Need an unlikely integer

echo paginate_links([
    'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
    'format' => '?paged=%#%',
    'current' => max(1, get_query_var('paged')),
    'total' => $query->max_num_pages,
]);

Conclusion

By combining ACF with WP_Query, you can build robust and flexible filtering systems tailored to your project’s needs. Whether you’re creating a real estate website, an e-commerce store, or a blog, these techniques will help you deliver dynamic and personalized content to your users.

How to Create a Condition in WordPress for Mobile Devices

If you're looking to create a custom condition in WordPress that targets mobile devices, you're in the right place. Whether you want to apply specific styles, load different scripts, or display certain elements only on mobile, WordPress offers several ways to detect mobile devices and conditionally load resources or content.

In this post, we'll explore a few methods to create conditions for mobile devices using CSS, JavaScript, and WordPress built-in functions.

1. Using CSS Media Queries

CSS media queries are the most common way to target mobile devices. By specifying a max-width or min-width, you can change the style of your website based on the screen size.

For instance, you can use the following CSS code to apply styles for mobile devices:

  
@media (max-width: 768px) {
    /* Mobile-specific styles */
    .your-element {
        background-color: blue;
    }
}

This code targets devices with a screen width of 768px or less, which typically corresponds to tablets and smartphones. Inside the @media block, you can define any CSS styles that you want to apply to mobile devices only.

2. Using JavaScript to Detect Mobile Devices

Sometimes, you may need to apply functionality based on the device type. For this, JavaScript is an excellent option. You can detect the window width or use more sophisticated mobile-detection methods.

Here's a simple JavaScript code to detect mobile devices based on the screen width:

  
if (window.innerWidth <= 768) {
    // Code for mobile devices
    document.body.style.backgroundColor = 'blue';
}

This code checks if the window width is less than or equal to 768px and applies specific actions if the condition is true. You can replace the action with any JavaScript code you need to run for mobile users.

3. Using wp_is_mobile() to Load Mobile-Specific Content

WordPress provides a built-in function called wp_is_mobile(), which checks if the user is on a mobile device. This can be particularly useful when you want to conditionally load scripts or styles only on mobile devices.

Here's an example of how to use wp_is_mobile() in your theme’s functions.php file to enqueue mobile-specific styles:

  
function my_mobile_script() {
    if ( wp_is_mobile() ) {
        // Enqueue mobile-specific styles or scripts
        wp_enqueue_style( 'mobile-style', get_template_directory_uri() . '/css/mobile.css' );
    }
}
add_action( 'wp_enqueue_scripts', 'my_mobile_script' );

The wp_is_mobile() function returns true if the user is visiting the site from a mobile device, and false otherwise. This makes it easy to load stylesheets or JavaScript files tailored for mobile users only.

4. Using Conditional Tags and JavaScript

If you prefer to implement a more custom approach, you can also use JavaScript alongside WordPress conditional tags. For example, you can use the is_page() or is_single() conditional tags to target specific pages and then apply mobile-specific styles or functionality:

  
if ( is_page( 'your-page-slug' ) && wp_is_mobile() ) {
    // Code for mobile users on this specific page
}

This ensures that only mobile users visiting specific pages on your site get the custom styles or functionality.

Conclusion

Creating a condition for mobile devices in WordPress can be done in several ways depending on the needs of your project. Whether you use CSS media queries, JavaScript detection, or WordPress-specific functions like wp_is_mobile(), you can optimize your site’s content for mobile users easily.

By using these techniques, you can ensure that your WordPress site delivers an optimized experience for mobile visitors, whether it’s through specific styling, script adjustments, or content modifications.

Top 10 Most Useful ACF Field Types and Their Use Cases - with Examples

ACF (Advanced Custom Fields) offers a wide variety of field types that empower WordPress developers to create dynamic, customizable, and user-friendly websites without extensive coding.

This post highlights the top 10 most useful ACF field types—Text, Textarea, Image, Gallery, Repeater, Select, Relationship, Date Picker, True/False, and Google Maps—along with practical use cases and code examples. These fields enable developers to build features like custom galleries, FAQs, event schedules, toggles, location maps, and much more.

By leveraging these fields effectively, you can significantly enhance the functionality and flexibility of your WordPress sites, catering to diverse project needs.

1. Text Field

Use Case

Perfect for single-line inputs like titles, headings, or simple text information.

Example

A "Client Name" field for a testimonial custom post type.

  

2. Textarea Field

Use Case

Great for longer text, such as product descriptions or user comments.

Example

A "Short Bio" field for author profiles.

  

3. Image Field

Use Case

Ideal for adding images, like a featured image for a custom post type.

Example

A "Team Member Photo" for a staff directory.

  

    <?php echo esc_attr($image['alt']); ?>

4. Gallery Field

Use Case

Useful for showcasing multiple images, such as a portfolio or product gallery.

Example

A "Project Gallery" for displaying project images.

  

        <?php echo esc_attr($image['alt']); ?>
    

5. Repeater Field

Use Case

Allows for flexible, repeating sets of fields, like FAQs or timelines.

Example

A "FAQ Section" with questions and answers.

  

        

6. Select Field

Use Case

For predefined options, like categories or user roles.

Example

A "Service Type" dropdown for a services post type.

  

7. Relationship Field

Use Case

Connect related content, such as linking blog posts to a specific author.

Example

A "Related Articles" section for a blog post.

  

        
    

8. Date Picker Field

Use Case

Great for event scheduling or publishing dates.

Example

An "Event Date" field for an events custom post type.

  

9. True/False Field

Use Case

For toggling settings or boolean values, like showing or hiding a section.

Example

A "Featured Post" toggle for blog posts.

  

    


10. Google Maps Field

Use Case

Perfect for adding location data.

Example

A "Store Location" map for a store locator feature.

  

    

Summary

Summarize the versatility of ACF fields and encourage readers to explore these field types in their projects. Offer a downloadable code snippet or a demo project for added value.

Enhancing Elementor Forms with Custom Validation Code

Elementor Forms are versatile and easy to use, but sometimes, the default validation options are insufficient for unique requirements. Adding custom validation ensures better data accuracy and user experience. This guide demonstrates how to enhance your Elementor forms with both client-side (JavaScript) and server-side (PHP) validation.

Why Custom Validation?

Default validation in Elementor is useful but limited. Custom validation allows you to:

  • Enforce specific rules (e.g., custom patterns for email or phone numbers).
  • Validate data against external APIs.
  • Add complex conditions for form submission.

Adding Custom Validation

Step 1: Adding JavaScript for Frontend Validation

Frontend validation occurs before the form is submitted. Use JavaScript to prevent users from submitting incorrect data.

Example: Validate a Custom Field for Alphabets Only

  1. Add this JavaScript code to your site via a plugin like WPCode or your theme's customizer:
  
document.addEventListener('DOMContentLoaded', function () {
    const form = document.querySelector('.elementor-form');
    if (form) {
        form.addEventListener('submit', function (event) {
            const customField = document.querySelector('input[name="custom_field"]');
            if (customField && !/^[a-zA-Z]+$/.test(customField.value)) {
                event.preventDefault();
                alert('Please enter alphabets only in the custom field.');
            }
        });
    }
});

Explanation:

  • The script listens for the form’s submit event.
  • It checks if the input in custom_field matches the alphabet pattern.
  • If validation fails, form submission is prevented, and an alert is displayed.

Step 2: Adding PHP for Server-Side Validation

Server-side validation ensures that invalid data doesn't get saved, even if frontend validation is bypassed.

Example: Validate the Same Custom Field Server-Side

  1. Add this PHP code to your theme’s functions.php file or a custom plugin:
  
add_action('elementor_pro/forms/new_record', function($record, $handler) {
    $raw_fields = $record->get('fields');
    $custom_field_value = $raw_fields['custom_field']['value'];

    if (!preg_match('/^[a-zA-Z]+$/', $custom_field_value)) {
        // Stop the form from being processed
        wp_die('Validation failed: Only alphabets are allowed in the custom field.');
    }
}, 10, 2);

Explanation:

  • The action elementor_pro/forms/new_record triggers after the form submission.
  • The code retrieves the custom_field value and checks it using a regex pattern.
  • If validation fails, the submission is terminated, and an error message is displayed.

Testing and Debugging

  1. Test on Staging Environment:

    • Never test custom validation directly on the live site.
    • Use a staging site to test thoroughly.
  2. Use Debugging Tools:

    • Use browser developer tools (console) to debug JavaScript.
    • Enable WordPress debugging (WP_DEBUG) for PHP errors.

Adding custom validation to Elementor forms elevates their functionality, ensuring accurate data collection and a better user experience. By implementing both frontend and server-side validation, you can create robust forms tailored to your specific needs.

How to Integrate Third-Party APIs into Elementor Widgets – With Example

  • Briefly introduce Elementor and its flexibility in creating custom widgets.
  • Highlight the importance of integrating third-party APIs for dynamic and interactive content.
  • Provide a quick overview of what the blog post will cover.

Understanding the Basics

  • What is a third-party API?
  • Common use cases for APIs in Elementor widgets (e.g., fetching data, real-time updates, integrations).
  • Prerequisites:
    • Knowledge of PHP and JavaScript.
    • Access to an Elementor-powered WordPress site.
    • API credentials for the chosen third-party service.

Step-by-Step Guide

1. Setting Up the API

  • Obtain API keys and configure API access.
  • Example: Using a weather API like OpenWeatherMap or a news API like NewsAPI.

2. Creating a Custom Elementor Widget

  • Register a custom widget using Elementor's widget manager.
  • Example code snippet for creating a basic custom widget:
  

class Custom_API_Widget extends \Elementor\Widget_Base {
    public function get_name() {
        return 'custom_api_widget';
    }
    public function get_title() {
        return 'Custom API Widget';
    }
    public function get_icon() {
        return 'eicon-code';
    }
    public function get_categories() {
        return ['basic'];
    }
    protected function render() {
        // Widget rendering logic here
    }
}

3. Fetching Data from the API

  • Use wp_remote_get or curl for server-side API requests in PHP.
  • Example:
  
$response = wp_remote_get('https://api.example.com/data?key=API_KEY');
if (is_array($response) && !is_wp_error($response)) {
    $data = json_decode($response['body'], true);
    echo '
' . esc_html($data['example_field']) . '
'; }

4. Displaying API Data in the Widget

  • Render the API response dynamically in your Elementor widget’s render method.
  • Example: Displaying weather information or news headlines.

5. Styling and Testing

  • Add CSS classes and styles for a polished look.
  • Test the widget thoroughly for different API responses and edge cases.

Complete Example

  • Provide a fully functional example, such as:
    • A widget that displays live weather data.
    • A widget that fetches and displays trending news articles.
  • Include complete code snippets for the example.

Best Practices

  • Use caching to reduce API call frequency and improve performance.
  • Handle errors gracefully (e.g., display a fallback message if the API fails).
  • Secure API keys by storing them in environment variables or WordPress settings.

How to Add JavaScript Effects to Your Elementor Pages

Elementor is one of the most popular WordPress page builders, offering incredible flexibility for creating stunning websites. However, for more advanced customizations and interactivity, adding JavaScript effects can take your pages to the next level.

In this post, we’ll explore how to seamlessly integrate JavaScript into your Elementor pages, with practical examples you can try today.

Step 1: Why Use JavaScript with Elementor?

JavaScript allows you to:

  • Add custom animations.
  • Trigger actions based on user interactions (e.g., scroll, click).
  • Implement advanced effects like typing animations, modal popups, or dynamic sliders.

While Elementor includes built-in motion effects, JavaScript gives you the freedom to create unique and highly customized effects.

Step 2: Adding JavaScript to Elementor Pages

Option 1: Using Elementor’s Custom Code Feature

  1. Go to Elementor > Custom Code in your WordPress dashboard.
  2. Click Add New, enter a name for your script, and paste your JavaScript code.
  3. Choose where the code should load (<head> or <footer>).
  4. Assign the code to specific pages or the entire site.

Example: Adding a Scroll-to-Top Button

  
document.addEventListener('DOMContentLoaded', () => {
  const button = document.createElement('button');
  button.textContent = '↑ Top';
  button.style.cssText = 'position:fixed;bottom:20px;right:20px;padding:10px;display:none;background:#333;color:#fff;border:none;border-radius:5px;';
  document.body.appendChild(button);

  window.addEventListener('scroll', () => {
    button.style.display = window.scrollY > 200 ? 'block' : 'none';
  });

  button.addEventListener('click', () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  });
});

Option 2: Using the HTML Widget

  1. Drag an HTML widget onto your page in Elementor.
  2. Paste your JavaScript inside a <script> tag.
  3. Save and preview your changes.

Example: Creating a Typing Animation

  

Step 3: Common JavaScript Effects to Try

Fade-In Animations

This effect makes elements smoothly appear as they enter the viewport.

 
document.addEventListener('DOMContentLoaded', () => {
  const elements = document.querySelectorAll('.fade-in');
  const fadeInOnScroll = () => {
    elements.forEach((el) => {
      const rect = el.getBoundingClientRect();
      if (rect.top < window.innerHeight && rect.bottom > 0) {
        el.style.opacity = '1';
        el.style.transform = 'translateY(0)';
      }
    });
  };

  elements.forEach((el) => {
    el.style.opacity = '0';
    el.style.transform = 'translateY(20px)';
    el.style.transition = 'all 1s ease';
  });

  window.addEventListener('scroll', fadeInOnScroll);
  fadeInOnScroll();
});

Add the fade-in class to any Elementor element in the Advanced > CSS Classes section.

Smooth Scrolling for Anchor Links

Enable smooth scrolling when clicking an anchor link.

 
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
  anchor.addEventListener('click', function (e) {
    e.preventDefault();
    document.querySelector(this.getAttribute('href')).scrollIntoView({
      behavior: 'smooth'
    });
  });
});

Custom Cursor Effect

Make a custom cursor that follows the mouse.

 

Step 4: Tips for Better Performance

  1. Minify JavaScript Files: Use tools like UglifyJS or online services to reduce file size.
  2. Load Scripts Conditionally: Only load scripts on pages where they are needed.
  3. Async and Defer Attributes: Use async or defer when loading external scripts to improve page load speed.
 

Step 5: Debugging and Testing

  • Use browser developer tools (Inspect Element) to debug JavaScript issues.
  • Test on multiple browsers and devices to ensure compatibility.
  • Check for console errors and address them promptly.

JavaScript opens up endless possibilities for customizing your Elementor pages. Whether you’re adding animations, creating dynamic interactions, or enhancing navigation, the tips and examples shared here will help you get started.

Experiment with these effects, and don’t forget to optimize your scripts for performance. Let us know your favorite JavaScript effect in the comments below!

Speed Optimization: Using Custom Code for Lightweight Elementor Designs

Introduction

Speed optimization is essential for websites, particularly those built with Elementor. Slow-loading pages can negatively impact user experience and SEO, leading to higher bounce rates and lower conversion rates.

Why Speed Matters for Elementor Websites

Elementor is a powerful tool for building stunning websites, but without proper optimization, it can result in heavy, slow-loading pages. Slow websites harm user experience and affect your SEO rankings.

Best Practices for Speed Optimization

1. Optimizing Images

  • Use proper image formats (e.g., WebP) for faster loading.
  • Compress images without losing quality using tools like TinyPNG.
  • Enable lazy loading for images to reduce initial load time.

2. Minimize CSS and JavaScript Files

  • Combine and minify CSS and JavaScript files.
  • Use custom code to load scripts only when necessary.
  • Leverage Elementor’s built-in options for disabling unused CSS/JS.

3. Caching Strategies

  • Implement browser and page caching to reduce load time.
  • Use caching plugins like WP Rocket or Autoptimize.
  • Consider using a Content Delivery Network (CDN) to serve static assets.

4. Optimizing Elementor Widgets

  • Disable unnecessary widgets and features to keep pages lightweight.
  • Use custom HTML/CSS instead of heavy Elementor widgets when needed.

5. Custom PHP Code for Speed

  • Use custom PHP code to handle complex functionalities instead of third-party plugins.
  • Ensure your server environment is optimized for WordPress.

6. Asynchronous Loading of JavaScript

  • Load non-essential scripts asynchronously to avoid blocking page rendering.

Tools for Testing and Monitoring Speed

Use tools like Google PageSpeed Insights, GTMetrix, and Pingdom to analyze website performance and identify bottlenecks. Regular monitoring ensures that your site remains fast.

Conclusion

Using custom code and implementing speed optimization best practices can drastically improve your Elementor website's performance. Test and tweak your design regularly for better results.

Creating Sticky Headers in Elementor Using Custom Code

Sticky headers are an excellent way to improve user experience by keeping your navigation menu accessible as users scroll down the page. While Elementor Pro offers built-in sticky header functionality, you can achieve the same result with custom code for more flexibility or if you're using the free version of Elementor.

In this guide, we’ll show you how to create a sticky header in Elementor using custom CSS and JavaScript.

Why Use a Sticky Header?

  • Enhanced Navigation: Ensures the menu is always within reach.
  • Better UX: Keeps key information, like contact buttons or branding, visible.
  • Professional Look: Adds a polished feel to your website design.

Step 1: Create Your Header in Elementor

  1. Go to Templates > Theme Builder > Header in your WordPress dashboard.
  2. Design your header using Elementor.
  3. Add a unique CSS class to the header section, e.g., custom-sticky-header.

Step 2: Add Custom CSS

To make the header sticky, add the following CSS to your Customizer or Elementor’s Custom CSS panel:

  
.custom-sticky-header {
    position: sticky;
    top: 0;
    z-index: 9999;
    background-color: #fff; /* Adjust based on your design */
    transition: box-shadow 0.3s ease;
}

.custom-sticky-header.sticky-active {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

Explanation:

  • position: sticky; keeps the header fixed at the top of the viewport.
  • top: 0; ensures it sticks to the top.
  • z-index: 9999; ensures the header stays above other elements.
  • The .sticky-active class adds a shadow when the header becomes sticky.

Step 3: Add JavaScript for Sticky Effect

To dynamically apply the sticky-active class when the header becomes sticky, add the following JavaScript code:

  
document.addEventListener('DOMContentLoaded', function() {
    const header = document.querySelector('.custom-sticky-header');
    const offset = header.offsetTop;

    window.addEventListener('scroll', function() {
        if (window.scrollY > offset) {
            header.classList.add('sticky-active');
        } else {
            header.classList.remove('sticky-active');
        }
    });
});

Explanation:

  • This script detects when the header scrolls past its original position.
  • It toggles the sticky-active class based on the scroll position.

Step 4: Test Your Sticky Header

Customize the query for Elementor’s Posts Widget to display specific content.

  • Open your website and scroll to see the sticky header in action.
  • Ensure it works on both desktop and mobile devices.
  • Tweak the CSS and JavaScript for any adjustments.

Bonus: Smooth Scrolling for Sticky Headers

If you have anchor links in your sticky header, ensure smooth scrolling with this CSS:

  
html {
    scroll-behavior: smooth;
}

Wrapping Up

Creating a sticky header in Elementor using custom code is straightforward and offers endless customization possibilities. This approach works perfectly for users who prefer flexibility or are using the free version of Elementor.

Customizing Elementor Templates with PHP Snippets

Elementor is one of the most versatile page builders for WordPress, but sometimes you may need to go beyond its built-in features to achieve advanced customizations. That’s where PHP snippets come in handy. In this guide, we’ll show you how to customize Elementor templates using PHP snippets, allowing you to unlock more control over your website design and functionality.

Why Use PHP Snippets for Elementor Customizations?

  • Extend Functionality: Add dynamic features to your Elementor templates.
  • Improve Efficiency: Customize templates without relying on heavy plugins.
  • Maintain Flexibility: Make changes programmatically for unique requirements.

Prerequisites

Before diving in, ensure you have:

  1. A WordPress website with Elementor installed.
  2. A child theme to safely add custom PHP code.
  3. Basic understanding of PHP and WordPress hooks.

Common Scenarios for Using PHP Snippets in Elementor

1. Add Dynamic Data to Elementor Templates

Use PHP to inject dynamic content like custom post metadata or user information into your Elementor designs.

  
add_action( 'elementor/frontend/after_render', function( $element ) {
    if ( 'heading' === $element->get_name() && $element->get_settings( 'custom_css_class' ) === 'dynamic-heading' ) {
        echo '

' . get_post_meta( get_the_ID(), 'custom_meta_key', true ) . '

'; } } );

Explanation:

  • This snippet checks if the element is a heading with a specific CSS class and appends dynamic content from custom metadata.

2. Replace Default Elementor Templates

Replace Elementor templates programmatically for specific post types.

  
add_filter( 'template_include', function( $template ) {
    if ( is_singular( 'custom_post_type' ) ) {
        $custom_template = locate_template( 'custom-single-template.php' );
        if ( $custom_template ) {
            return $custom_template;
        }
    }
    return $template;
} );

Explanation:

  • This code replaces the default Elementor single template for a custom post type.

3. Customize the Content Wrapper Classes

Modify the wrapper classes for Elementor templates to match your theme’s structure.

  
add_filter( 'elementor/frontend/container_attributes', function( $attributes ) {
    if ( isset( $attributes['class'] ) ) {
        $attributes['class'] .= ' custom-wrapper-class';
    }
    return $attributes;
} );

Explanation:

  • This snippet appends custom classes to the container attributes for additional styling.

4. Add Custom Query Parameters to Elementor Posts Widget

Customize the query for Elementor’s Posts Widget to display specific content.

  
add_action( 'elementor/query/custom_query', function( $query ) {
    $query->set( 'meta_key', 'featured' );
    $query->set( 'meta_value', 'yes' );
} );

Explanation:

  • This code customizes the query to display only posts with the meta key featured set to yes.

Best Practices for Adding PHP Snippets

  • Always Use a Child Theme: Avoid modifying core theme files to ensure updates won’t overwrite your customizations.
  • Backup Your Website: Test PHP snippets on a staging site before deploying them to production.
  • Leverage Hooks and Filters: Utilize WordPress hooks and Elementor APIs for seamless integration.

Wrapping Up

Customizing Elementor templates with PHP snippets gives you unparalleled control over your website’s functionality and design. By leveraging the examples above, you can tailor your Elementor templates to meet your unique requirements.

If you found this guide helpful, feel free to share it with others or drop a comment below with your questions or customization ideas!