Is it possible to override a function in a theme, from a plugin? I've been struggling to find an example of how I would achieve the above.
If anyone could shed any light it would be really helpful.
edit: Adding some code
So this is my function which allows the cart in woocommerce to update using ajax:
add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cartplus_fragment', '1');
function woocommerce_header_add_to_cartplus_fragment( $fragments ) {
global $woocommerce;
$basket_icon = esc_attr($instance['basket_icon']);
ob_start();
?>
<a class="cartplus-contents" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" onclick="javscript: return false;" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>
<?php
$fragments['a.cartplus-contents'] = ob_get_clean();
return $fragments;
}
However, some themes also have a similar function built in - in these themes my code stops working which seems strange as I use the above code twice in my plugin (one is a variation of the above) and they work fine together. This is the code built in to the theme:
add_filter('add_to_cart_fragments', 'woocommerce_cart_link');
function woocommerce_cart_link() {
global $woocommerce;
ob_start();
?>
<a href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> <?php _e('in your shopping cart', 'woothemes'); ?>" class="cart-button ">
<span class="label"><?php _e('My Basket:', 'woothemes'); ?></span>
<?php echo $woocommerce->cart->get_cart_total(); ?>
<span class="items"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count); ?></span>
</a>
<?php
$fragments['a.cart-button'] = ob_get_clean();
return $fragments;
}
Unless the function is meant to be overridden, no. This is basic PHP. You can't redefine a function. If you try you will get a fatal error.
Parts of WordPress are written to be overwritten. Look at
/wp-includes/pluggable.php
. Every function in there is wrapped in aif( !function_exists(...) )
conditional. Unless your theme did the same, and some do for some functions, you can't overwrite.Look around for filters that might help you instead.
Looking at your code, you should be able to unhook that. Just make sure to hook the unhook late enough. That is not a good solution, though since you are breaking theme functionality and also must know the know the names of all the hooked functions that themes are using.
Is there something in
$fragments
, or in$_POST
or$_GET
or anything else, that you can use to conditionally run your code, leaving the rest alone.