Reputation: 315
How can I override the plugin function inside the theme folder's 'functions.php' file?
Below is my code:
if(!function_exists('userphoto_filter_get_avatar')){
function userphoto_filter_get_avatar($avatar, $id_or_email, $size, $default){
global $userphoto_using_avatar_fallback, $wpdb, $userphoto_prevent_override_avatar;
if($userphoto_using_avatar_fallback)
return $avatar;
if(is_object($id_or_email)){
if($id_or_email->ID)
$id_or_email = $id_or_email->ID;
// Comment
else if($id_or_email->user_id)
$id_or_email = $id_or_email->user_id;
else if($id_or_email->comment_author_email)
$id_or_email = $id_or_email->comment_author_email;
}
if(is_numeric($id_or_email))
$userid = (int)$id_or_email;
else if(is_string($id_or_email))
$userid = (int)$wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_email = '" . mysql_escape_string($id_or_email) . "'");
if(!$userid)
return $avatar;
// Figure out which one is closest to the size that we have for the full or the thumbnail
$full_dimension = get_option('userphoto_maximum_dimension');
$small_dimension = get_option('userphoto_thumb_dimension');
$userphoto_prevent_override_avatar = true;
$img = userphoto__get_userphoto($userid, (abs($full_dimension - $size) < abs($small_dimension - $size)) ? USERPHOTO_FULL_SIZE : USERPHOTO_THUMBNAIL_SIZE, '', '', array(), '');
$userphoto_prevent_override_avatar = false;
if($img)
return $img;
return $avatar;
}
}
And when I activate the plugin, it is giving me a fatal error:
Cannot redeclare
userphoto_filter_get_avatar()
.
What am I doing wrong?
Upvotes: 2
Views: 7133
Reputation: 1260
Add your custom override code to a must-use plugin.
Pluggable functions defined in plugins can be overridden only by using another plugin or a must-use plugin. Adding the code to another plugin is not reliable. So, it is best to use a must-use plugin.
Note that pluggable functions that are defined in the WordPress core can be overridden by using a function of the same name in our plugin or theme.
The code added to the theme's functions.php file will be executed later i.e. after the plugin code has been executed. So, adding our overwrite function in the theme file will trigger the cannot redeclare
error.
Reason:
The execution order of various WordPress actions is specified in the Plugin_API/Action_Reference. As we can see from here, the simplified execution order is
So, to override functionality defined in the second hook (i.e. in the plugin), we need to redefine it in a hook that gets executed before it (i.e in the must-use plugins).
Upvotes: 10