Backend Developer Docs

Actions

dz-add-providers

This action helps you adding new providers to the plugin.

dz-providers-loaded

This action runs after every provider has been loaded and ordered correctly.
W3SocialLogin::$providers contains all available providers.
W3SocialLogin::$enabledProviders contains only the enabled providers.

Connect Flow actions/filters

{{provider-id}}_login_action_before

This action run first after the user clicked the social login button. It has only one parameter, the current provider. It extends from the W3SocialProvider class.

{{provider-id}}_login_redirect_url

A filter to override the login redirect url. It has two parameters:

  • Fixed redirect URL, if set
  • current provider

It returns the new redirect URL.
Example:

add_filter('facebook_login_redirect_url', function($redirectUrl, $provider){ return $redirectUrl;}, 10, 2);

{{provider-id}}_register_redirect_url

It’s the same as the {{provider-id}}_login_redirect_url. It has the same two parameters, but it happens upon registration:

  • Fixed redirect URL, if set
  • current provider

dz_register_new_user

This happens when a new user is registered with any of the providers. Parameteres:

  • $user_id
  • provider instance

dz_{{provider-id}}_register_new_user

This action runs when the user registers with the given provider. Parameters:

  • $user_id
  • provider instance

dz_{{provider-id}}_auto_link_allowed

This filter can prevent linking the user accounts automatically for a user when it returns false.
Parameters:

  • $isAutoLinkAllowed
  • current provider instance
  • $user_id

dz_{{provider-id}}_is_login_allowed

This filter can prevent the login for the user when it returns false.
Parameters:

  • $isAutoLoginAllowed
  • current provider instance
  • $user_id

dz_login

This action runs when a user logs in with any of the providers.
Parameters:

  • $user_id
  • provider instance

dz_{{provider-id}}_login

This action runs when a user logs in with the given provider.
Parameters:

  • $user_id
  • provider instance
  • access_token

dz_pre_register_new_user

This action runs before the new user is registered.
Parameters:

  • W3SocialUser class instance

dz_is_register_allowed

This filter defines whether the user registration is allowed or not.
Parameters:

  • boolean
  • provider instance

Available since: 3.0.4

dz_{{provider-id}}_link_user

This action runs when a user link the account to a given provider, registration with the given provider also triggers this hook.
Parameters:

  • $user_id
  • provider id

dz_unlink_user

This action runs when a user unlinks a social media account from a certain provider.
Parameters:

  • $user_id
  • provider id
  • unlinked social media id

dz_registration_user_data

This filter can be used for overriding certain userdata before the registration or preventing the registration.
Parameters:

  • $userData – associative array – username and email
  • $provider – provider instance, that can be used to retrieve some data of current user.
  • $error – error object, that can be used for preventing the registration.

dz_disabled_register_redirect_url

This filter can be used for overriding the URL where the user will be redirected, if the registration is disabled.
Parameters:

  • $redirectUrl – string – the url of the page

dz_disabled_register_error_message

This filter can be used for overriding the message that is displayed when the registration is disabled with W3 Social Login.
Parameters:

  • $errorMessage – string – the error message

Starting from version 1.0 passing “false” in the return value can be used for disabling the default error message!

dz_{{provider-id}}_auth_url_args

This filter can be used for overriding authorization URL arguments of each provider.
Parameters:

  • $args – associative array – contains the current authorization URL arguments.

dz_match_social_account_to_user_id

This filter can be used for overriding the User ID that the social account should be linked to.
Parameters:

  • $user_id – the ID of the WordPress account where the social account should be linked to
  • social user instance
  • current provider instance

dz_disabled_login_redirect_url

This filter can be used for overriding the URL where the user will be redirected, if the login is disabled.
Return value:

  • string – the URL where the user should be redirected

dz_disabled_login_error_message

This filter can be used for overriding the message that is displayed when the login is disabled with W3 Social Login.
Return value:

  • string – the error message

dz_already_linked_error_message

This filter can be used for overriding the message that is displayed when a person tries to connect with a social media account, that’s email address is registered on the site and has another social media account from the same kind already linked.
Return value:

  • string – the error message

dz_bypass_cache_url

This filter can be used for adding custom GET parameters to the redirect URL, when the “Bypass cache on redirect” setting is enabled. By default the name of the parameter is “dz_bypass_cache” and its value is a unique hash.
Parameters:

  • $url – string – the URL where the user should be redirected to

Return value:

  • string – the URL where the user should be redirected to ( To attempt bypassing the cache, at least one GET parameter should be added into the URL! )

Example:


add_filter('dz_bypass_cache_url', function ($url) { return add_query_arg(array("abc" => "123"), $url); });

dz_connect_button_custom_attributes

You can use this filter to add custom attributes to the connect button.

Example:

add_filter('dz_connect_button_custom_attributes', function ($attr, $provider) {
    $attr['attrbute'] = "value";
    return $attr;
}, 10, 2);

Using the trackerdata shortcode function

W3 Social Login allows you to do custom actions when the user logs in using the login buttons. Add the trackerdata attribute to the shortcode:

[w3_social_login trackerdata="my-tracker-data"]

Then you can write custom codes to change the user role based on the page where the user has registered or to save down extra information.

Example: using trackerdata to identify the page the user registered

For this you’ll need to use the shortcode with a custom trackerdata value. In this tutorial the registered_from value will be used

[w3_social_login trackerdata="registered_from"]

Then you’ll need to set up cookies to save down the URL of the current page:

<script type="text/javascript">
    function setCookie(name,value,days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
setCookie('registered_from', '<?php global $wp; echo home_url( $wp->request ) ?>', 7);</script>

And you’ll also need a PHP code to work with the cookie. The nsl_register_new_user action runs just before the registration process is finished, so you can use it to get the tracker data and add a new user meta.

<?php add_action('dz_register_new_user', function ($user_id) {
    if (W3SocialLogin::getTrackerData() == "registered_from") {
        $user = new WP_User($user_id);
        add_user_meta($user->ID, 'registered_from', $_COOKIE['registered_from']);
    }
});?>

You could create a custom plugin to add these codes. You can find a working sample below:

<?php
/*
Plugin Name: DZ Social Login 
Description: Track the page where users logged in using W3 Social Login
Version: 1.0
 */

add_action('wp_head', 'set_custom_cookie');
function set_custom_cookie(){
    ?>
    <script type="text/javascript">
    function setCookie(name,value,days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
setCookie('registered_from', '<?php global $wp; echo home_url( $wp->request ) ?>', 7);</script>
    <?php
};

add_action('dz_register_new_user', function ($user_id) {
    if (W3SocialLogin::getTrackerData() == "registered_from") {
        $user = new WP_User($user_id);
        add_user_meta($user->ID, 'registered_from', $_COOKIE['registered_from']);
    }
});

Validate Username

You can add custom validation to the entered username using the dz_validate_username filter.

Example:

add_filter('dz_validate_username', function ($isValid, $username, $errors) {
    if (strlen($username) < 6) {
        $errors->add('invalid_username', '' . __('ERROR') . ':' . __('Sorry, username must contain at least 6 characters.'));
        $isValid = false;
    }
    return $isValid;
}, 10, 3);

Override the userdata (username/email) before registration

You can override the username or the email in the $userData using the dz_registration_user_data filter.

Example:

add_filter('dz_registration_user_data', function($userData, $provider){
    $userData['username']=$provider->getAuthUserData('first_name').'-'.$provider->getAuthUserData('last_name');
            
    return $userData;
},10,2);

Prevent registration with certain email domain

You can either allow or prevent registration with certain email domains using the dz_registration_user_data filter.

Example – disable registration with the gmail.com email domain:

add_filter('dz_registration_user_data', function ($user_data, $provider, $errors) {
    /**
     * List of banned domains. Multiple domains can be separated with commas e.g.: "gmail.com","yahoo.com"
     */
    $banned_domains = array("gmail.com");
    if (isset($user_data['email']) && !empty($user_data['email']) && is_email($user_data['email'])) {
        $email_parts = explode('@', $user_data['email']);
        if (in_array($email_parts[1], $banned_domains )) {
            /**
            * The error message.
            */
            $errors->add('invalid_email', '' . __('ERROR') . ': ' . __('Sorry, registration with this email domain is not allowed!'));
            return $user_data;
        }
    } else {
        $errors->add('invalid_email', '' . __('ERROR') . ': ' . __('Sorry, email is missing or invalid!'));
    }

    return $user_data;
}, 10, 3);

Asking custom fields before the registration

You can use W3 Social Login to ask custom information form the users before the registration process is finished and you can also validate this data.

In the example below you can see how to ask the favorite color of the person who registers.

<?php

add_action('dz_before_register', function ($provider) {
    /** @var $provider W3SocialProvider */

    /**
     * You must return true if you want to add custom fields
     */
    add_filter('dz_registration_require_extra_input', function ($askExtraData) {
        return true;
    });

    add_filter('dz_registration_validate_extra_input', function ($userData, $errors) {
        /** @var $errors WP_Error */


        $isPost = isset($_POST['submit']);

        if ($isPost) {
            /**
             * You must add an error if your fields are not filled or does not fulfill your validation.
             * If no errors added, that means that the register form is fine.
             */

            if (!empty($_POST['favorite_color']) && is_string($_POST['favorite_color'])) {
                $userData['favorite_color'] = $_POST['favorite_color'];
            } else {
                $userData['favorite_color'] = '';
                $errors->add('favorite_color_missing', '<strong>' . __('ERROR') . '</strong>: Favorite Color can not be empty.', array('form-field' => 'favorite_color'));
            }
        } else {
            /**
             * Fill up user data with default values to prevent the notice in the form
             */
            $userData['favorite_color'] = '';
        }

        return $userData;
    }, 10, 2);

    /** You can use dz_registration_form_start and dz_registration_form_end action.  */
    add_action('dz_registration_form_start', function ($userData) {
        ?>
        <p>
            <label for="favorite_color">Favorite Color<br/>
                <input type="text" name="favorite_color" id="favorite_color" class="input"
                       value="<?php echo esc_attr(wp_unslash($userData['favorite_color'])); ?>" size="20"/></label>
        </p>
        <?php
    });

    /**
     * $user_id contains the created user's id
     * $userData contains the previously validated input
     */
    add_action('dz_registration_store_extra_input', function ($user_id, $userData) {
        add_user_meta($user_id, 'favorite_color', $userData['favorite_color']);
    }, 10, 2);
});

Redirect user on login depending on its role

By combining the ‘dz_login’ action and the ‘{{provider-id}}_login_redirect_url’ filter, you can control where the user with a specific role should land.

In this example, you can see a basic code snippet which redirects the users with the “subscriber” role to a custom link.

<?php

function redirectWhenRoleMatches($user_id, $provider) {
    $user       = get_userdata($user_id);
    $user_roles = $user->roles;

    if (in_array('subscriber', $user_roles, true)) {
        add_filter($provider->getId() . '_login_redirect_url', function () {
            return 'https://example.com/page-for-subscribers';
        });

        //Or you can also use it by specifying the id of the provider directly, like:
        /*
        add_filter('facebook_login_redirect_url', function () {
            return 'https://example.com/page-for-subscribers';
        });
        */
    }
}
add_action('dz_login', 'redirectWhenRoleMatches', 10, 2);

Exclude URL from Fixed redirect url – for Login/Register setting

In this example, you can see a basic code snippet which will prevent the Fixed redirect url – for Login/Register setting from redirecting to the specified URL, if the Google button is pressed on the ‘https://example.com/checkout’ page:

<?php

function excludeUrlFromFixedRedirect($fixedRedirectUrl, $provider) {
    $pageWhereButtonWasClicked = DZ\Persistent\Persistent::get('redirect');
    $excluded_url              = 'https://example.com/checkout';
    if ($pageWhereButtonWasClicked && strpos($pageWhereButtonWasClicked, $excluded_url) !== false) {
        return false;
    }

    return $fixedRedirectUrl;
}
//excludes the URL from Fixed redirect url - for Login, when login happens with the Google provider
add_filter('google_login_redirect_url', 'excludeUrlFromFixedRedirect', 10, 2);
//excludes the URL from Fixed redirect url - for Register, when login happens with the Google provider
add_filter('google_register_redirect_url', 'excludeUrlFromFixedRedirect', 10, 2);

Display simple statistics in the Dashboard page

The code snippet below can display a simple statistics on the Dashboard page ( /wp-admin/index.php ) showing the number of connections per provider and the total number of connections across all enabled providers.

<?php
add_action('wp_dashboard_setup', 'soc_net_dashboard_widget');
function soc_net_dashboard_widget() {
    wp_add_dashboard_widget('soc_net_widget', 'Social network user account connections', 'soc_net_dashboard_widget_function');
}


function soc_net_dashboard_widget_function() {
    global $wpdb;

    $providers = $wpdb->get_results("SELECT UPPER(su.type) as type, COUNT(ID) AS cnt FROM {$wpdb->prefix}social_users AS su GROUP BY su.type ORDER BY cnt DESC", OBJECT);
    $total = 0;
    ?>
    <table class="widefat striped" width="100%">
        <thead>
        <tr>
            <th>Provider</th>
            <th width="30%" class="column-posts">Connections</th>
        </tr>
        </thead>
        <tbody>
        <?php if (!empty($providers)) {
            foreach ($providers as $provider) { ?>
                <tr>
                    <td><?php echo $provider->type; ?></td>
                    <td class="manage-column num"><?php echo $provider->cnt; ?></td>
                </tr>
                <?php

                $total++;

            }
        } ?>
        </tbody>
        <tfoot>
        <tr>
            <td>Total accounts:</td>
            <td class="manage-column num"><?php echo $total; ?></td>
        </tr>
        </tfoot>
    </table>

    <?php
}

( Thank you Vlado for submitting this code snippet! )