I’m trying to optimize my functions.php file as I have a Woocommerce site with a bunch of customizations to the theme. Currently, my functions look like the following:
add_action('wp_footer', 'enqueue_product_modals');
function enqueue_product_modals() {
global $product; //Accessing the Global
$product_id = $product->get_id();
if (is_product()) {
//Standard Modal:
require_once 'modal-product.php';
if (has_term('guitar-pickups', 'product_cat', $product_id)) {
include_once 'modal-polarity.php';
};
if (has_term('mini-humbuckers', 'product_cat', $product_id)) {
include_once 'modal-minihum.php';
};
}
}
add_action('woocommerce_after_single_product_summary', function () {
global $product; //Accessing the Global Again
$name = $product->get_name();
if (have_comments()) {
echo '<p class="reviews-tagline">Trying to leave a review for our ' . $name . '? <a class="expand" data-toggle="collapse" data-target="#review_form_wrapper" >Leave one here.</a></p>';
}
}, 50);
etc.
I understand accessing the global $product
multiple times is bad practice. So, I started to rewrite functions by declaring the global $product
at the top of my functions.php file, (like I would in JS) and passing it in to each individual function like so:
global $product;
add_action('wp_footer', 'enqueue_product_modals');
function enqueue_product_modals($product) {
$product_id = $product->get_id();
if (is_product()) {
// code here...
}
}
add_action('woocommerce_after_single_product_summary', function ($product) {
$name = $product->get_name();
if (have_comments()) {
//code here
}, 50);
The problem is that now all functions are broken and when doing a var_dump($product)
inside each function $product is an empty string. I am now positive I don’t know what I’m doing. Can someone offer any assistance on the correct way to access the $product global in each function…or a better way?
Edit:
I also tried passing the $post
object, so rewriting the function like so, but it’s still an empty string:
add_action('wp_footer', 'enqueue_product_modals');
function enqueue_product_modals($post) {
if (is_product()) {
$product = wc_get_product($post->ID); // hoping to use this
var_dump($post); //Still empty String
}
}