Tag: wordpress

  • Manage WooCommerce Store Completely From the Frontend

    Manage WooCommerce Store Completely From the Frontend

    Have you ever wished you could run your own/client WooCommerce store without ever logging into the WordPress admin?

    If you’ve handed your store over to a shop manager — or you’re the owner who just wants to add a product and check today’s sales without wading through menus, plugins, and settings you don’t need — the standard WooCommerce admin can feel like a lot. Too many screens. Too much clutter. Too many places a non-technical team member can accidentally break something.

    That’s exactly the problem StoreSuite sets out to solve. It gives you a clean, modern frontend dashboard where you (and your team) can manage everything — products, orders, coupons, categories, and analytics — from one place. No wp-admin. No clutter. Just your store.

    And here’s the part most people don’t expect: StoreSuite ships features for free that other store-management dashboards usually lock behind a Pro plan — including AI content and image generation, full variable product support, real-time analytics, and CSV export. Let’s walk through it.



    What is StoreSuite?

    StoreSuite is a WordPress plugin that adds a frontend store-management dashboard to your WooCommerce shop. Instead of giving your team access to the WordPress backend, you give them a single page on your own site where they can do everything day-to-day:

    • Add and edit products (every type — simple, variable, grouped, external)
    • View, create, and edit orders
    • Build and manage coupons
    • Organize categories, tags, brands, and attributes
    • Watch real-time sales numbers and leaderboards
    • Generate product titles, descriptions, and images with AI

    It requires WooCommerce, it’s fully compatible with WooCommerce HPOS (High-Performance Order Storage), and access is gated by the manage_woocommerce capability — so only administrators and shop managers get in.

    StoreSuite frontend dashboard



    Why Manage Your Store From the Frontend?

    A quick honest list of why this matters:

    • Less risk. Your shop manager/owner never sees plugin settings, theme files, or anything they could break. They see your store — nothing else.
    • Less clutter. No third-party plugin notices, no unrelated admin menus. StoreSuite even strips out theme and conflicting plugin styles on its own pages so the dashboard stays clean and fast.
    • Faster work. Everything is one or two clicks away. Add a product, check an order, spin up a coupon — without hunting through the backend.

    Now let’s look at what you can actually do.



    1. A Dashboard That Shows Your Store at a Glance

    Log in, land on the dashboard, and within a few seconds you know how your store is doing. That’s the whole idea.

    The dashboard home greets you with your store’s pulse — a row of performance boxes showing the numbers that matter: net sales, orders, average order value, returns, discounts, and products sold. Each box carries a small percentage badge so you can see how today compares to yesterday (or this month vs. last month, or this December vs. last December — your choice).

    Below that sits a net-sales chart you can switch between line and bar views and group by day, week, or month. Then come the leaderboards — top products, top categories, top customers, top coupons — and a Recent Orders table so you can spot anything that needs attention.

    Finally, a Quick Actions grid gives you one-click shortcuts to the things you do most: add a product, view orders, create a coupon, and more.



    2. Complete Product Management

    This is where most store owners spend their time, and StoreSuite makes it effortless.

    Products list in StoreSuite

    The Products list is your home base. Every product appears in a clean table with its image, name, category, status, SKU, a color-coded stock badge, price (with the old price crossed out on sale items), and type. From here you can:

    • Search any product by name instantly
    • Filter by category, product type, stock status, or brand — and combine them (for example, out-of-stock products in the Clothing category)
    • Quick edit the basics (name, price, stock, status) right from the list
    • Use bulk actions to edit, trash, or export many products at once



    Add or edit any product type

    StoreSuite handles every WooCommerce product type — simple, variable, grouped, and external/affiliate. The add/edit form walks you through everything top to bottom, but only the title is truly required, so you can start simple and polish later.

    You get full control over pricing (including scheduled sales that turn themselves on and off), inventory with low-stock thresholds and backorders, shipping, upsells and cross-sells, catalog visibility, and more.

    Editing a variable product

    Variable products get special love: manage attributes and variations, run bulk actions, and use generate-all-variations to create every size/color combination in one click — something many “free” dashboards simply don’t offer.



    3. AI That Writes and Designs For You

    Here’s StoreSuite’s standout feature — and it’s completely free.

    Writing product descriptions is the part most store owners dread. StoreSuite hands it to AI:

    • Per-field generation — a “Generate with AI” button on the product title, short description, and long description. Each one opens an editable suggestion you can tweak, regenerate, or step through previous suggestions with a history pager.
    • All-in-one generator — type a single hint and StoreSuite drafts the title, short description, and long description together.
    • AI image generation — describe a featured or gallery image, preview it, regenerate, and drop it straight into your media library.

    AI settings page

    You stay in control with a dedicated AI settings page, where you can turn generation on or off per field and set your own custom instructions for each text field and for images.

    StoreSuite uses a “bring your own AI” approach — it’s built on the WordPress 7.0 core AI connector, so generation runs on the provider and keys you configure. (If your site is on an older WordPress version, the AI features simply hide themselves.)



    4. Full Order Management

    Orders list in StoreSuite

    Orders are front and center. From the Orders section you can:

    • View every order with its number, customer, date, total, and a color-coded status badge
    • Open any order to see full customer and line-item details
    • Create a new order by hand — perfect for phone or in-person sales
    • Edit existing orders when something needs changing

    Because StoreSuite is HPOS-compatible, it works smoothly even on high-volume stores using WooCommerce’s modern order storage.



    5. Coupons, Categories, Tags, Brands & Attributes

    Everything that keeps your catalog organized is here too.

    Coupons in StoreSuite

    • Coupons — create, edit, and manage WooCommerce discount codes with all the usual rules.
    • Categories, Tags, and Brands — add, edit, and list them without leaving the dashboard. The lists even refresh instantly if changes are made elsewhere (admin, REST API, an import).
    • Product Attributes — manage attributes and their terms, ready to power your variable products.

    To keep the sidebar tidy, Categories, Brands, and Tags are neatly nested under the Products menu.



    6. Export Your Products to CSV

    Need your catalog for reporting, accounting, or migrating to another store? StoreSuite includes CSV product export with a configurable export modal — select what you need and download it. Again, free, no upsell.



    7. Make It Your Own

    StoreSuite admin settings

    From WooCommerce → StoreSuite in your WordPress admin, you can shape the dashboard to fit your brand and workflow:

    • Branding — add a sidebar logo (expanded) and a sidebar icon (collapsed) from the media library.
    • Color palettes — choose a predefined palette or build a custom one with live preview.
    • Dashboard widgets — switch performance boxes and leaderboards on or off; show eight meaningful numbers instead of fifteen noisy ones.
    • Pagination — control how many items show per page on each list.

    There’s also a collapsible sidebar that toggles between a full menu and a slim icon-only rail, with your preference remembered in the browser.



    How to Get Started

    Setting up StoreSuite takes about two minutes:

    1. Install and activate WooCommerce (if you haven’t already).
    2. Install and activate StoreSuite from Plugins → Add New (search “StoreSuite”).
    3. On activation, StoreSuite automatically creates a dashboard page with the You have no permission to view this page shortcode and selects it for you. If it didn’t, create a page, add the shortcode, and publish.
    4. Go to WooCommerce → StoreSuite → General and confirm your dashboard page is selected, then Save Changes.
    5. Visit that page while logged in with store-management permissions — and you’re managing your store from the frontend.

    If a dashboard URL ever returns a 404, just go to Settings → Permalinks and click Save Changes to refresh the routes.



    Final Thoughts

    Running a WooCommerce store shouldn’t mean living inside the WordPress admin. StoreSuite gives you and your team a clean, fast, frontend home for everything that matters — products, orders, coupons, your whole catalog, and real-time analytics — plus AI that writes your descriptions and creates your images.

    And it does all of it with no feature gates, no trial limits, and no upsell. The premium-grade tools other dashboards charge for are simply included.

    If you’ve been looking for the easiest way to manage your WooCommerce shop completely from the frontend, give StoreSuite a try — your morning store check-in is about to get a whole lot shorter.

    Get StoreSuite free from the WordPress plugin directory →

  • How to Set Up an Existing WordPress VIP Site Locally on macOS

    How to Set Up an Existing WordPress VIP Site Locally on macOS

    A quick guide to cloning a live WordPress VIP site to your MacBook for local development. Follow these commands in order.

    Step 1: Install the Required Tools

    Install Docker Desktop and VIP-CLI:

    brew install --cask docker
    npm install -g @automattic/vip
    

    After installing Docker, open it from your Applications folder so it starts running in the background.

    Verify all tools are installed:

    vip -v && node -v && npm -v && docker --version

    Please skip Step 2 & Step 3 if you are setting up an existing WordPress VIP site from a backup instead of cloning the WPVIP GitHub repository.

    Step 2: Log In to VIP-CLI

    vip logout   # in case of stale session
    vip login
    

    The logout command clears any old session. vip login opens a browser window to authenticate with your VIP account.

    Step 3: Clone the Site Repository

    cd ~/Sites
    git clone git@github.com:wpcomvip/your-site-name.git
    cd your-site-name
    

    Replace your-site-name with the actual repository name from your VIP application.

    Step 4: Create the Local Environment

    vip dev-env create --slug=your-site
    

    You can name –slug anything unique you want but follow the rules lowercase letters, numbers, and hyphens only. No spaces, no underscores, no special characters. Common conventions: wp-vip-test-site.

    A setup wizard will appear. Match production for PHP version, WordPress version, and multisite settings. When asked for the application code source, choose Local folder and provide the path to your cloned repo.

    • Site title: anything
    • Multisite: match production
    • PHP version: match production
    • WordPress version: match production
    • Source for application code: choose Local folder and give it the absolute path to your cloned repo (e.g. /Users/you/Sites/your-site-name)
    • Source for mu-plugins: auto (pulls VIP’s mu-plugins automatically)
    • Source for VIP MU plugins: auto

    Step 5: Start the Environment

    vip dev-env start --slug=your-site
    

    Once started, you’ll see the local site URL, login credentials, and an auto-login link. Save these for later.

    Step 6: Import the Database

    vip dev-env import sql /path/to/file.sql --slug=your-site
    

    Replace /path/to/file.sql with the actual path to your SQL dump on your Mac.

    Step 7: Import Media Files

    vip dev-env import media /path/to/wp-content/uploads --slug=your-site
    

    Replace /path/to/wp-content/uploads with the path to the uploads folder on your Mac. The folder should contain year-numbered subfolders (2023/, 2024/, etc.).

    Done

    Your local copy of the VIP site is now running. Open the site URL shown after vip dev-env start and log in with the credentials provided.

    Day-to-Day Useful Commands

    Once your environment is set up, these are the commands you’ll use most often.

    # List all your local environments
    vip dev-env list
    
    # Check status, URLs, and credentials
    vip dev-env info --slug=your-site
    
    # Start the environment
    vip dev-env start --slug=your-site
    
    # Stop the environment (frees up RAM and CPU)
    vip dev-env stop --slug=your-site
    
    # Run any WP-CLI command inside the container
    vip dev-env exec --slug=your-site -- wp plugin list
    vip dev-env exec --slug=your-site -- wp cache flush
    vip dev-env exec --slug=your-site -- wp user list
    
    # Create a new admin user
    vip dev-env exec --slug=your-site -- wp user create yourname you@example.com --role=administrator
    
    # Check site URL after import
    vip dev-env exec --slug=your-site -- wp option get siteurl
    vip dev-env exec --slug=your-site -- wp option get home
    
    # Search and replace URLs in the database
    vip dev-env exec --slug=your-site -- wp search-replace 'old-url' 'new-url' --skip-columns=guid
    
    # Delete all manually imported media files (host path - faster)
    rm -rf ~/.local/share/vip/dev-environment/your-site/uploads/*
    
    # Delete all manually imported media files (container path - alternative)
    vip dev-env exec --slug=your-site -- rm -rf /wp/wp-content/uploads/*
    
    # Destroy the environment completely
    vip dev-env destroy --slug=your-site
    
    # Update tooling to the latest version
    npm update -g @automattic/vip
    

    For official documentation, visit docs.wpvip.com/vip-local-development-environment.

  • How WordPress is Preparing for the AI Era

    How WordPress is Preparing for the AI Era

    We know WordPress is powerful, because of its thousands of plugins, APIs & functions but they are scattered. As a human we understand this ecosystem because we read docs to know how they works, features etc. But AI doesn’t work on this way. Because its not possible to know all the available WordPress plugins working procedure top to bottom. So the WordPress core AI team is taking a much smarter approach to use AI within the WordPress project. This approach is called AI Building Blocks for WordPress. The goal of the AI Building Blocks is Simple: Give AI a clear, secure, and standardized way to understand what WordPress can do and to do it safely.

    They are working on the three core technologies that work together:

    • PHP AI Client SDK & WordPress AI Client
    • Abilities API
    • MCP Adapter



    PHP AI Client SDK:

    Currently there are many AI providers (OpenAI, Anthropic, Gemini, etc.) in the market and each has its own API & configurations process. If a developer want to enable AI features to their own plugins they need to implement the API integration from scratch. Also the developers need to implement each providers separately for their plugins. Developers rebuilds the same infrastructure: provider integrations, API key management. Admin enter the same credentials multiple time and multiple places for each separate plugins.

    On the other hand, the PHP AI Client SDK creates one unified PHP interface that works with multiple AI models. To use the SDK everything will be centralizes, one credentials system for all plugins. The WordPress site admins choose which AI services they want to configure & use from a single place. So, developers can focus on building AI features, not AI infrastructure. Developers don’t lock themselves into a single AI provider.



    WordPress AI Client:

    An AI client and API for WordPress to communicate with any generative AI models of various capabilities using a uniform API. Built on top of the PHP AI Client, adapted for the WordPress ecosystem while following WordPress Coding Standards and best practices. Features of the WordPress AI Client:

    • WP Prompt Builder – A WordPress-friendly way to create and manage AI prompts using PHP, following WordPress coding standards.
    • Admin Settings Page – A WordPress Admin settings screen to store AI provider API keys.
    • Auto API Key Setup – Automatically uses API keys saved in WordPress settings.
    • Standard HTTP Client – Uses the WordPress HTTP API in a PSR-compatible way.
    • JavaScript API – Front-end JS prompt builder that talks with the server through the WP REST APIs.



    Abilities API:

    A typical WordPress website might could have lots of plugins installed & activated, each introducing unique functionality. But there’s no standardized way for these components to express their capabilities. An AI assistant has no systematic way to discover that. To solve this problem, the Abilities API establishes a standardized format for registering the capabilities of plugins and themes in a common structure, something like below:

    • What the plugin or feature does.
    • What inputs it needs.
    • What output it returns.
    • Which permission require to run it.

    This makes it easier for AI to automatically discover WordPress features. It transforms WordPress from an isolated collection of functionalities and plugins into an interconnected, discoverable system.



    MCP Adapter:

    Once WordPress knows its own abilities by Abilities API, the next step is letting AI assistants use them. That’s the job of the MCP Adapter.
    MCP (Model Context Protocol) is an open standard that defines how applications expose tools to AI models. The MCP Adapter translates WordPress abilities into a format that AI assistants like ChatGPT, Claude or Gemini can understand. AI assistants can discover, understand, and execute actions like creating posts, managing media, and moderating comments, all through the standardized protocol. So, Content creators can manage their WordPress sites conversationally, while developers can automate complex workflows across systems. Agencies can build sophisticated integrations, from content migration to performance optimization.



    These three AI Building Blocks work together by the following way:

    • PHP/WordPress AI Client SDK talks to AI models.
    • Abilities API defines what WordPress can do.
    • MCP Adapter exposes those abilities to AI assistants safely.



    AI Experiments

    If you want to experiments all the AI Building Blocks in one place then you can try AI Experiments Plugin. It serves as both a powerful tool for users and a reference implementation for developers, demonstrating how the PHP AI Client SDK, Abilities API, and MCP Adapter work together in practice.


    Human Written Content Certified

  • How to Migrate Your Local WordPress Site to a Vito Web Panel Server

    How to Migrate Your Local WordPress Site to a Vito Web Panel Server

    Follow this step-by-step guide to migrate your local WordPress website to a live server using the Vito Web Panel.




    1. Add Your SSH Key to the Vito Server

    First, generate an SSH key on your device and add it to the SSH Settings section inside the Vito server panel.



    2. Create a WordPress Site in Vito

    Create a new WordPress site from the Vito Web Panel.
    For example, assume your live domain is:

    wp-site.com
    
    Enter fullscreen mode

    Exit fullscreen mode



    3. Connect to the Vito Server via SSH

    Open your terminal and log in to your server using the following command:

    ssh vito@{your.server.ip}
    
    Enter fullscreen mode

    Exit fullscreen mode

    Once logged in, you will be at the server’s root directory.
    To list your created websites, run:

    ls or ls -la
    
    Enter fullscreen mode

    Exit fullscreen mode



    4. Navigate to Your Website Directory

    Enter your WordPress site directory:

    cd wp-site.com
    
    Enter fullscreen mode

    Exit fullscreen mode



    5. Remove the Existing wp-content Folder

    Delete the default wp-content directory:

    rm -rf wp-content
    
    Enter fullscreen mode

    Exit fullscreen mode



    6. Prepare Your Local wp-content for Upload

    Create a ZIP file of your local site’s wp-content folder.

    Before uploading, open the folder in a code editor and perform a search & replace:

    • Replace all instances of: local-wp-site.test with wp-site.com

    • Then replace: http://wp-site.com with https://wp-site.com



    7. Upload the wp-content ZIP to the Server

    Use SCP to upload the zipped folder to your server:

    scp ~/Herd/local-wp-site/wp-content.zip vito@ {your.server.ip}:/home/vito/wp-site.com/
    
    Enter fullscreen mode

    Exit fullscreen mode



    8. Unzip the Uploaded File

    From your project root directory, unzip the file:

    unzip wp-content.zip
    
    Enter fullscreen mode

    Exit fullscreen mode

    Now your site files are ready.



    9. Export Your Local Database

    Run the following command to export your local database:

    mysqldump -u root -p local_site_db > local_site_db.sql
    
    Enter fullscreen mode

    Exit fullscreen mode



    10. Upload the Database to the Server

    Upload the exported SQL file:

    scp ~/Herd/local-wp-site/local_site_db.sql vito@ {your.server.ip}:/home/vito/
    
    Enter fullscreen mode

    Exit fullscreen mode



    11. Import the Database Into the Live Server

    Run the following command to import your SQL file into the live database:

    mysql -u db_user_name -p wp_site_db < /home/vito/local_site_db.sql
    
    Enter fullscreen mode

    Exit fullscreen mode

    You will be prompted for the database password. Enter it, and the import will proceed.



    12. Update URLs Using WP-CLI

    Navigate back to your project’s root directory and run the following WP-CLI commands:

    wp search-replace 'local-wp-site.test' 'wp-test.com'
    
    Enter fullscreen mode

    Exit fullscreen mode

    wp search-replace 'http://wp-test.com' 'https://wp-test.com'
    
    Enter fullscreen mode

    Exit fullscreen mode

    This ensures all old local URLs are correctly replaced with the live domain URLs.


    Your migration is now complete!

  • A Beginner’s Guide to Global State Management in WordPress Gutenberg

    A Beginner’s Guide to Global State Management in WordPress Gutenberg

    When building complex WordPress block editor (Gutenberg) applications, managing state efficiently becomes crucial. This is where @wordpress/data comes into play. It allows you to manage and share global state across different blocks and components in your WordPress application.

    If you’re new to managing global state or using @wordpress/data, don’t worry! This blog post will walk you through the basics of reducers, actions, and selectors, explaining how to use them to manage state in WordPress.

    @wordpress/data provides a way to store, update, and access data globally, allowing different components or blocks to share and interact with the same data.



    Key Concepts in @wordpress/data

    To understand how to use @wordpress/data, we need to understand three main concepts: reducers, actions, and selectors. These form the core of how state is managed and updated.



    Actions:

    An action is like an instruction or command that tells the reducer what to do. It’s simply an object that has two parts:

    1. A type that indicates what kind of change is happening (e.g., add, remove, update).
    2. A payload that contains the data needed for that change (e.g., which item to add).

    Here’s an example of how actions might look in our cart example:

    const actions = {
        addToCart(item) {
            return {
                type: 'ADD_TO_CART', // Action type
                item // Payload: the item to add to the cart
            };
        },
        removeFromCart(itemId) {
            return {
                type: 'REMOVE_FROM_CART', // Action type
                itemId // Payload: the ID of the item to remove
            };
        }
    };
    
    Enter fullscreen mode

    Exit fullscreen mode

    In short: Actions tell the reducer what needs to change in the state.



    Reducers:

    A reducer is like a manager of your state. Whenever something changes in your application (e.g., a user adds a block or disables a feature), the reducer listens for that change and updates the state accordingly.

    What does a reducer do? It takes the current state and an action, then returns a new state based on the action.
    Here’s an example of a simple reducer that manages a shopping cart:

    const reducer = (state = { cart: [] }, action) => {
        switch (action.type) {
            case 'ADD_TO_CART':
                return {
                    ...state, // Keep the existing state
                    cart: [...state.cart, action.item] // Add the new item to the cart
                };
            case 'REMOVE_FROM_CART':
                return {
                    ...state,
                    cart: state.cart.filter((item) => item.id !== action.itemId) // Remove the item from the cart
                };
            default:
                return state; // Return the unchanged state for unknown actions
        }
    };
    
    Enter fullscreen mode

    Exit fullscreen mode

    In short: The reducer defines how the state changes when specific actions are dispatched.



    Selectors:

    A selector is a function that retrieves or selects specific data from the state. When your components need to access data (like displaying the items in the cart), they use a selector to fetch that data from the store.

    For example, a selector to get all the cart items might look like this:

    const selectors = {
        getCartItems(state) {
            return state.cart; // Return the cart items from the state
        }
    };
    
    Enter fullscreen mode

    Exit fullscreen mode

    In a component, you would use this selector to access the cart data like this:

    const cartItems = useSelect((select) => select('my-store').getCartItems());
    
    Enter fullscreen mode

    Exit fullscreen mode

    In short: A selector is a helper function that lets you access specific data from the state.



    Step by Step Guide to Implement Global State in Gutenberg with @wordpress/data

    Now that we’ve covered the basics, let’s walk through how you can implement these concepts in a Gutenberg block or component. We’ll set up a simple store with @wordpress/data, manage some state, and use actions and selectors to interact with that state.

    Step 1: Define Your Initial State
    First, we need to define the initial state of our store. This is the default data that our application starts with:

    const DEFAULT_STATE = {
        cart: []
    };
    
    Enter fullscreen mode

    Exit fullscreen mode

    Step 2: Create Actions
    Next, we define the actions that we will use to update the state. In our case, we’ll define two actions: one to add an item to the cart and another to remove an item.

    const actions = {
        addToCart(item) {
            return {
                type: 'ADD_TO_CART',
                item
            };
        },
        removeFromCart(itemId) {
            return {
                type: 'REMOVE_FROM_CART',
                itemId
            };
        }
    };
    
    Enter fullscreen mode

    Exit fullscreen mode

    Step 3: Create the Reducer
    The reducer listens for dispatched actions and updates the state accordingly. Here’s our reducer, which updates the cart when actions are dispatched:

    const reducer = (state = DEFAULT_STATE, action) => {
        switch (action.type) {
            case 'ADD_TO_CART':
                return {
                    ...state,
                    cart: [...state.cart, action.item]
                };
            case 'REMOVE_FROM_CART':
                return {
                    ...state,
                    cart: state.cart.filter((item) => item.id !== action.itemId)
                };
            default:
                return state;
        }
    };
    
    Enter fullscreen mode

    Exit fullscreen mode

    Step 4: Create Selectors
    Selectors help retrieve specific data from the state. For example, if we want to get all items in the cart, we would create a selector like this:

    const selectors = {
        getCartItems(state) {
            return state.cart;
        }
    };
    
    Enter fullscreen mode

    Exit fullscreen mode

    Step 5: Create and Register the Store
    Finally, we’ll create and register the store with the @wordpress/data package. This will make the store globally accessible across your WordPress site.

    import { createReduxStore, register } from '@wordpress/data';
    
    const store = createReduxStore('my-cart-store', {
        reducer,
        actions,
        selectors,
    });
    
    register(store);
    
    Enter fullscreen mode

    Exit fullscreen mode

    Step 6: Using the Store in Components
    Once the store is registered, you can use it in your Gutenberg blocks or components. For example, to add an item to the cart:

    import { useDispatch } from '@wordpress/data';
    
    const { addToCart } = useDispatch('my-cart-store');
    addToCart({ id: 1, name: 'Sample Item' });
    
    Enter fullscreen mode

    Exit fullscreen mode

    To fetch the items in the cart:

    import { useSelect } from '@wordpress/data';
    
    const cartItems = useSelect((select) => select('my-cart-store').getCartItems());
    
    Enter fullscreen mode

    Exit fullscreen mode



    Conclusion

    By understanding the roles of reducers, actions, and selectors, you can easily manage global state in your WordPress Gutenberg projects using @wordpress/data. This structured approach allows you to manage data more efficiently, making your blocks and components more powerful and interactive.

    With @wordpress/data, you have a reliable and scalable solution for handling state across your entire WordPress application. Give it a try in your next Gutenberg project!

  • How to Implement a WooCommerce AJAX Direct “Buy Now” Button

    How to Implement a WooCommerce AJAX Direct “Buy Now” Button

    When you’re running an online store using WooCommerce, making the purchasing process as seamless as possible is crucial. One effective way to do this is by adding a “Buy Now” button that allows customers to directly purchase a product without navigating through multiple pages. This blog will walk you through creating a WooCommerce AJAX “Buy Now” button using the provided code snippets.



    Step 1: Add the “Buy Now” Button

    First, you need to add a custom “Buy Now” button on your WooCommerce product pages. We’ll do this by hooking into the woocommerce_after_add_to_cart_button action, which places our button right after the standard “Add to Cart” button.

    Here’s the PHP code snippet:

    add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );
    function add_content_after_addtocart() {
        $current_product_id = get_the_ID();
        $product = wc_get_product( $current_product_id );
    
        if( $product->is_type( 'simple' ) ){
            echo '<button data-id="'.$current_product_id.'" class="buy-now button"><i class="matico-icon-toys"></i>'.__('Buy Now', 'woocommerce').'</button>';
        }
    }
    
    Enter fullscreen mode

    Exit fullscreen mode

    Explanation:

    • We use the woocommerce_after_add_to_cart_button hook to insert our “Buy Now” button right after the “Add to Cart” button.
    • The get_the_ID() function retrieves the current product ID, and wc_get_product() gets the product details.
    • We check if the product is of type simple and then render the button with the appropriate data-id attribute and a custom icon.



    Step 3: Enqueue the Script

    Next, you need to enqueue the script in your theme to ensure it’s loaded properly on your WooCommerce pages. Here’s how to do it:

    wp_enqueue_script('matico-child-script', get_stylesheet_directory_uri() . '/assets/js/script.js', array( 'jquery', 'scrollfix-script' ),  $matico_version, true);
    
    wp_localize_script( 'matico-child-script', 'matico_child_script_obj',
        array( 
            'checkout_page_url' => wc_get_checkout_url(),
        )
    );
    
    Enter fullscreen mode

    Exit fullscreen mode

    Explanation:

    • wp_enqueue_script() is used to load our custom script file (script.js), which contains the jQuery code.
    • wp_localize_script() passes PHP data to the script, such as the checkout page URL, allowing us to use it within the script.



    Step 2: Handle the AJAX Request

    Finally, we’ll handle the button click event using jQuery. The jQuery script sends an AJAX request to WooCommerce, which adds the product to the cart and then redirects the user directly to the checkout page.

    Here’s the jQuery code snippet:

    (function ($) {
        var MaticoChildThemeConfig = {
            init: function () {
                this.bindEvents();
            },
            bindEvents: function () {
                $(document).on('click', '.buy-now', this.handleBuyNowClick);
            },
            handleBuyNowClick: function (event) {
                event.preventDefault();
    
                var $button = $(this),
                    quantity = parseFloat($button.closest('.quantity').find('.qty').val()) || 1,
                    productID = $button.data('id');
    
                var data = {
                    product_id: productID,
                    quantity: quantity,
                };
    
                $.ajax({
                    type: 'POST',
                    url: wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'),
                    data: data,
                    dataType: 'json',
                    beforeSend: function () {
                        $button.addClass('loading');
                    },
                    success: function (res) {
                        if (res.error && res.product_url) {
                            window.location.href = res.product_url;
                        } else {
                            window.location.href = matico_child_script_obj.checkout_page_url;
                        }
                    }
                });
            }
        };
    
        MaticoChildThemeConfig.init();
    })(jQuery);
    
    Enter fullscreen mode

    Exit fullscreen mode

    Explanation:

    • When the “Buy Now” button is clicked, we prevent the default action to avoid page reload.
    • We gather the product ID and quantity from the current product page.
    • An AJAX request is sent to WooCommerce’s add_to_cart endpoint, which adds the product to the cart.
    • If the product is successfully added, we redirect the user to the checkout page. If there’s an error (e.g., the product is no longer available), the user is redirected to the product page.



    Conclusion

    By implementing the above steps, you can create a “Buy Now” button that streamlines the purchasing process for your customers. This feature is particularly useful in boosting conversions by reducing the number of clicks and pages a customer needs to navigate before completing a purchase.

  • How to Install WordPress and Essential Plugins Using WP-CLI

    How to Install WordPress and Essential Plugins Using WP-CLI

    Setting up a WordPress site can be time-consuming if done manually, but with WP-CLI, the process becomes much faster and more efficient. In this tutorial, I’ll show you how to install WordPress along with a few essential plugins using a single command sequence.



    Step 1: Download WordPress Core

    First, you’ll need to download the WordPress core files. This command will download WordPress to a directory called mywebsite.

    wp core download --path=mywebsite
    
    Enter fullscreen mode

    Exit fullscreen mode



    Step 2: Create the Configuration File

    Navigate into the newly created mywebsite directory, and create the wp-config.php file with your database credentials:

    cd mywebsite
    wp config create --dbname=silk --dbuser=root --dbpass=root
    
    Enter fullscreen mode

    Exit fullscreen mode



    Step 3: Create the Database

    Now, create the database using the following command:

    wp db create
    
    Enter fullscreen mode

    Exit fullscreen mode



    Step 4: Install WordPress

    Install WordPress using your local URL, site title, and admin credentials:

    wp core install --url=mywebsite.test --title="Site Title" --admin_user=admin --admin_password=admin --admin_email=mywebsite@welabs.dev
    
    Enter fullscreen mode

    Exit fullscreen mode



    Step 5: Install and Activate Plugins

    Finally, install and activate the necessary plugins. In this example, we’ll install WooCommerce and Dokan Lite:

    wp plugin install woocommerce --activate
    wp plugin install dokan-lite --activate
    
    Enter fullscreen mode

    Exit fullscreen mode



    All-in-One Command Sequence

    For your convenience, here’s the entire process in one continuous block of code. Just copy and paste the code below into your terminal to install WordPress and a few plugins with a single command.

    wp core download --path=mywebsite
    cd mywebsite
    wp config create --dbname=silk --dbuser=root --dbpass=root
    wp db create
    wp core install --url=mywebsite.test --title="Site Title" --admin_user=admin --admin_password=admin --admin_email=mywebsite@welabs.dev
    wp plugin install woocommerce --activate
    wp plugin install dokan-lite --activate
    
    Enter fullscreen mode

    Exit fullscreen mode

    Prerequisite: Install WP-CLI to you machine.