Skip to content

Instantly share code, notes, and snippets.

@hslaszlo
Created May 30, 2019 17:00
Show Gist options
  • Save hslaszlo/376314a33788c1b0cd275fea590f94e0 to your computer and use it in GitHub Desktop.
Save hslaszlo/376314a33788c1b0cd275fea590f94e0 to your computer and use it in GitHub Desktop.
Programmatically add product to cart
<?php
/*
Plugin Name: Programmatically add product to cart
Plugin URI: https://www.webmenedzser.hu
Description: Add a product to the cart programmatically if the user role is subscriber
Version: 1.0
Author: Radics Ottó
Author URI: https://www.webmenedzser.hu
License: GPLv3
*/
function add_product_to_cart_programmatically() {
if (current_user_can('subscriber')) {
$productID = 39;
$productCartID = WC()->cart->generate_cart_id( $productID );
$inCart = WC()->cart->find_product_in_cart( $productCartID );
if ( !$inCart ) {
WC()->cart->add_to_cart( $productID );
}
}
}
add_action( 'template_redirect', 'add_product_to_cart_programmatically', 10, 0 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment