I am trying to modify the head and foot of my WooCommerce pages. I have an if
statement that is supposed to target the shop and cart of WooCommerce, but it isn’t. If I modify the PHP after the if
statement nothing changes. But if I modify the PHP in the else
statement is works:
This doesn’t work:
<?php if (function_exists('woocommerce')): ?>
<?php if (is_cart() || is_shop()): ?>
<?php get_template_part('inc/CHANGE'); ?>
<?php endif ?>
<?php else: ?>
<?php get_template_part('inc/page-header'); ?>
<?php endif ?>
This does work:
<?php if (function_exists('woocommerce')): ?>
<?php if (is_cart() || is_shop()): ?>
<?php get_template_part('inc/page-header'); ?>
<?php endif ?>
<?php else: ?>
<?php get_template_part('inc/CHANGE'); ?>
<?php endif ?>
I think the function WooCommerce might not be properly defined, because this also works:
<?php if (is_cart() || is_shop()): ?>
<?php get_template_part('inc/header-shop'); ?>
<?php else: ?>
<?php get_template_part('inc/page-header'); ?>
<?php endif ?>
Your edit got me to this idea, there indeed is no function called »woocommerce«, there is a class »WooCommerce
« though. One thing to be aware of is, that the check has to late enough, so that plug-ins are actually initialized, otherwise – obviously – the class won’t exists and the check returns false
. So your check should look like this:
if ( class_exists( 'WooCommerce' ) ) {
// some code
} else {
/ more code
}
On the WooCommerce documentation page »Creating a plugin for WooCommerce« I have found this:
/**
* Check if WooCommerce is active
**/
if (
in_array(
'woocommerce/woocommerce.php',
apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
)
) {
// Put your plugin code here
}
Personally I think it is not nearly as reliable as checking for the class. For obvious reasons, what if the folder/file name is different, but should work just fine too. Besides if you do it like this, then there is an API function you can use, fittingly named is_plugin_active()
. But because it is normally only available on admin pages, you have to make it available by including wp-admin/includes/plugin.php
, where the function resides. Using it the check would look like this:
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
// some code
} else {
/ more code
}