Add cross-sell products to all products in WooCommerce – no plugin required
To add cross-sell products to all products in WooCommerce using PHP code, follow these steps:
Step 1: Find the Product IDs for Cross-Sell Products
- Go to WooCommerce > Products:
- In the WordPress admin panel, navigate to “Products” under “WooCommerce”.
- Identify Product IDs:
- On the product list page, you will see a column with the product IDs. If the ID column is not visible, you can identify the product ID by:
- Editing a product: Click on a product name to go to the edit page. In the URL bar, you will see something like
post=123
– the number 123 is the product ID. - Product list view: Hover over the product name in the list. The product ID will be displayed in the URL at the bottom of the browser.
- Editing a product: Click on a product name to go to the edit page. In the URL bar, you will see something like
- On the product list page, you will see a column with the product IDs. If the ID column is not visible, you can identify the product ID by:
Step 2: Use the Product IDs in PHP Code
- Copy the Product IDs:
- Note down the IDs of the products you want to add as cross-sell.
- Customize the PHP Code:
- Replace the placeholder IDs in the
$cross_sells
array with your noted product IDs.
- Replace the placeholder IDs in the
Here’s the updated PHP code with a placeholder for product IDs:
function add_cross_sells_to_all_products() {
$cross_sells = array(123, 456, 789); // Replace with your product IDs for cross-sell
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
$product_id = get_the_ID();
update_post_meta($product_id, '_crosssell_ids', $cross_sells);
endwhile;
wp_reset_query();
}
add_action('init', 'add_cross_sells_to_all_products');
Step 3: Insert the PHP Code
- Log in to the WordPress Admin Panel.
- Navigate to Appearance > Theme Editor.
- Find the
functions.php
file:- In the theme files section on the right, find and click on
functions.php
.
- In the theme files section on the right, find and click on
- Paste the PHP Code:
- Paste the above code at the end of the
functions.php
file.
- Paste the above code at the end of the
- Save Changes:
- Click “Update File” to save the changes.
After following these steps, the selected cross-sell products will be added to all products in your WooCommerce store.
Note:
- Always back up your
functions.php
file before making any changes. - Using a child theme is recommended to prevent your changes from being overwritten during theme updates.