Here’s the code that gets the selected payment method using the WooCommerce Blocks data store in your React component :
import { useSelect } from '@wordpress/data';
const selectedPaymentMethod = useSelect((select) => {
const store = select('wc/store/payment');
if (!store) {
console.log('Payment store not found');
return null;
}
const activePaymentMethod = store.getActivePaymentMethod();
console.log('Selected Payment Method:', activePaymentMethod);
return activePaymentMethod;
}, []);
How it works :
- useSelect is a React hook from @wordpress/data that lets you access data from WordPress data stores.
- select(‘wc/store/payment’) gets the WooCommerce payment store.
- store.getActivePaymentMethod() returns the currently selected payment method ID.
- The code logs the active payment method to your browser console for debugging.
Usage :
- You can use the selectedPaymentMethod variable in your component to conditionally render UI or trigger logic based on the selected payment method.
In the following example we toggle between COD and BACS to test our code is working with the WooCommerce checkout blocks payment options.
useSelect is used in most WooCommerce extensions.
Related Solutions :
Leave a Reply