Showing posts with label wordpress. Show all posts
Showing posts with label wordpress. Show all posts

Saturday, 17 May 2014

customizing user action drop down in admin menu

We may need to customize the gravatar or provide the custom link to the profile page in the the user action drop down under the user name (right top corner) in admin bar, In order to do the customization we can use the wp_before_admin_bar_render action hook as shown below.

add_action( 'wp_before_admin_bar_render', 'custom_remove_my_account' );
if (!function_exists('custom_remove_my_account')) {
    function custom_remove_my_account() {
        global $wp_admin_bar;
        $wp_admin_bar->remove_node('user-actions');  /*Removed the default user action dropdown*/
        custom_admin_bar_my_account_menu($wp_admin_bar);
    }
}


/**

custom_admin_bar_my_account_menu method alters the user action dropdown
*/ 
if (!function_exists('custom_admin_bar_my_account_menu')) {
    function custom_admin_bar_my_account_menu( $wp_admin_bar ) {
        $user_id      = get_current_user_id();
        $current_user = wp_get_current_user();
        $profile_url  = get_permalink( 6 ); /*Here i just provided the custom page link as profile page*/

        if ( ! $user_id )
        return;

        $wp_admin_bar->add_group( array(
            'parent' => 'my-account',
            'id'     => 'user-actions',
            )
        );

        $user_info  = get_avatar( $user_id, 64 );
        $user_info .= "<span class='display-name'>{$current_user->display_name}</span>";

        if ( $current_user->display_name !== $current_user->user_login )
        $user_info .= "<span class='username'>{$current_user->user_login}</span>";

        $wp_admin_bar->add_menu( array(
            'parent' => 'user-actions',
            'id'     => 'user-info',
            'title'  => $user_info,
            'href'   => $profile_url,
            'meta'   => array(
                'tabindex' => -1,
                ),
            )
        );
        $wp_admin_bar->add_menu( array(
            'parent' => 'user-actions',
            'id'     => 'edit-profile',
            'title'  => __( 'Edit My Profile' ),
            'href' => $profile_url,
            )
        );
        $wp_admin_bar->add_menu( array(
            'parent' => 'user-actions',
            'id'     => 'logout',
            'title'  => __( 'Log Out' ),
            'href'   => wp_logout_url(home_url()),
            )
        );
    }
}

Just paste the abovecode in either plugin files or in the functions.php ( theme file ).
 

Thursday, 4 July 2013

Integrate wordpress media uploader

We can use native wordpress Media uploader in our themes and plugins to upload the image from the media library.

Following code will include the required scripts and stylesheets for the Media uploader thickbox.

if(!function_exists('custom_uploader_scripts')) {
    function custom_uploader_scripts() {

        wp_enqueue_script('jquery');
        wp_enqueue_script('media-upload');
        wp_enqueue_script('thickbox');
    }
}
add_action('admin_print_scripts', 'custom_uploader_scripts');

if(!function_exists('custom_uploader_styles')) {
    function custom_uploader_styles() {
        wp_enqueue_style('thickbox');
    }
}

add_action('admin_print_styles', 'custom_uploader_styles');


Following lines will be used to display the  input text and the Browse button.


<input type="text" name="input_image_path" id="input_image_path" value=""/>
<input type="button" name="trigger_image_button" id="trigger_image_button" value="Browse" />
Following code can be used in the separate JS file or can be used in the same php file. This will trigger the media uploader and will insert the image url into the text box on image selection.



<script type="text/javascript">

 (function($){

    $('#trigger_image_button').click(function() {
        tb_show('', 'media-upload.php?referer=custom-upload&amp;type=image&TB_iframe=true');
       
window.send_to_editor = function(html) {
        imgurl = $('img',html).attr('src');
        $('#input_image_path').val(imgurl);
        tb_remove();
        return false;
    });

})(jQuery);

</script>




In media uploader, by default the save button text will be "Insert into Post", we can customize the text of the button through the following code


if(!function_exists('custom_options_setup')) {
    function custom_options_setup() {
        global $pagenow;
        if ('media-upload.php' == $pagenow || 'async-upload.php' == $pagenow) {
            // Now we'll replace the 'Insert into Post Button inside Thickbox'
            add_filter( 'gettext', 'replace_thickbox_text' , 1, 2 );
          
        }
    }
}


add_action( 'admin_init', 'custom_options_setup' );

if(!function_exists('replace_thickbox_text')) {
    function replace_thickbox_text($translated_text, $text ) {  
        if ( 'Insert into Post' == $text ) {
            $
referer = strpos( wp_get_referer(), 'custom-upload' );
           
/* Here the custom-upload text is appended to the url through above JS code. Its to make filter to apply only for our page without disturbing the other media uploaders. */
            if ( $referer != '' ) {
                return __('Use this Image', 'custom');
            }
        }

        return $translated_text;
    }
}



Monday, 1 July 2013

Block user role login

We can block the user login by the Role. This will work before the user name and password validation. So we can block the user before the validation for this we need to assign the user to particular role in this I used the "blocked" role which is custom one you can make any role to get blocked.


Sample code to block the user by role.Just paste the following code in either plugin files or in the functions.php ( theme file )


 add_filter('wp_authenticate_user', 'custom_block_user_role_login', 10, 2);
if(!function_exists('custom_block_user_role_login')) {
    function custom_block_user_role_login($user, $password) {
       
        $role = $user->wp_capabilities;


/*
* In below code "blocked" is the user role you can assign it to another role 
* which you want to get blocked
*/
        if(array_key_exists('blocked', $role)) {
            return new WP_Error('block_user', __('You are Blocked.'));
        }
        return $user;
    }
}

Friday, 7 June 2013

Conditional Stylesheet

 By default wp_enqueue_style function  does not provide any option to include stylesheet based on browser but we can do it  with the help of $wp_styles global variable.


add_filter( 'wp_enqueue_scripts', 'custom_enqueue_scripts' );
if(!function_exists('custom_enqueue_scripts')) {
    function custom_enqueue_scripts() {
        wp_enqueue_style( 'conditionalstyle', get_stylesheet_directory_uri().'/css/conditional.css' );

        global $wp_styles;
        $wp_styles->registered['
conditionalstyle']->add_data( 'conditional', 'lt IE 8' );
    }
}

Thursday, 30 May 2013

Prevent plugins from update

We can prevent certain plugins from updating themselves or asking to be updated. It can be done using the http_request_args filter


if(!function_exists('custom_prevent_plugin_update_check')){

    function custom_prevent_plugin_update_check( $r, $url ) {
        if ( 0 === strpos( $url, 'http://api.wordpress.org/plugins/update-check/' ) ) {
            $to_be_blocked    = array('plugin-folder-name/plugin-filename.php');


/*Example: array('contact-form-7/wp-contact-form-7.php'). It will prevent contact-form-7  for update check.*/
/*We can block multiple plugins  by specifying their names in this array as above. */        

            if (!empty($to_be_blocked)){
                foreach ($to_be_blocked as $individual){
                    $plugins = unserialize( $r['body']['plugins'] );
                    unset( $plugins->plugins[$individual] );
                    unset( $plugins->active[array_search( $individual,
                               $plugins->active )] );
                    $r['body']['plugins'] = serialize( $plugins );
                }
            }
        }
        return $r;
    }


}


add_filter( 'http_request_args', 'custom_prevent_plugin_update_check',10, 2 );

Friday, 17 May 2013

Custom validation in user profile page

We can perform custom validation in user profile page. We can perform the validation through user_profile_update_errors hook.
 
if (!function_exists('custom_user_contact_validate')) {

    function custom_user_contact_validate(&$errors, $update = null, &$user = null) {

        if (!empty($_POST["action"]) && ($_POST["action"] == "adduser" || $_POST["action"] == "createuser"))
            return $errors;
      
        if (empty($_REQUEST['first_name'])) {
            $errors->add('Invalid Data', '<strong>ERROR</strong>: Please Enter your First Name');
        }

/*Here the field first name has been validated*/
    }

}
add_action('user_profile_update_errors', 'custom_user_contact_validate', 5);



Note: The validation added through this Hook will works while editing the user's profile page. Fields wont be validated while creating a user.

Thursday, 16 May 2013

Custom menu in admin bar

Our plugins may need to add a menu item for pointing to settings page in admin bar.  wp_before_admin_bar_render filter helps us to do that.

if(!function_exists('custom_admin_bar_menu')){
    function custom_admin_bar_menu() {
        global $wp_admin_bar;
            $wp_admin_bar->add_menu( array(
            'id' => 'my_settingspage',
            'title' => __('My settings'),
            'href' => admin_url('/plugingsettingspage.php')
        ) );
    }
}
add_action( 'wp_before_admin_bar_render', 'custom_admin_bar_menu' );



We can also make it as child to existing menu by adding the menu-id as a parent to that menu

Wednesday, 15 May 2013

Custom fields in user profile page

We can add custom fields to the user profile page as like the post types.
user_contactmethods filter will do the trick


if (!function_exists('custom_user_contactmethods')) {

    function custom_user_contactmethods($user_contactmethods) {
        return array_merge($user_contactmethods, array(
                    'address1' => __('Address Line1')

                   /*We can add multiple fields in this array.*/                      
                   )

        );
    }

}
add_filter('user_contactmethods', 'custom_user_contactmethods', 5, 1);





Note: The fields added through this filter will get appeared only while editing the user's profile page. It wont be available while creating a user.

Monday, 13 May 2013

Get current user role

Its easy to get the currently logged-in user role by using the global variable $current_user. Following function can be used to get the current user's role.

if(!function_exists('custom_get_current_user_role')) {
    function custom_get_current_user_role(){
         if(is_user_logged_in()) {
            global $current_user;
            $user_role = $current_user->roles[0];
            return $user_role;
        }
        return FALSE;
    }
}

Wednesday, 8 May 2013

Admin bar for non logged users

Its possible to display the admin bar for the non-logged-in users it can be easily done by using the show_admin_bar filter and admin_bar_menu hook.

Just paste the following code in either plugin files or in the functions.php ( theme file ).

if(!function_exists('custom_login_adminbar')){
    function custom_login_adminbar( $wp_admin_bar) {


        if ( !is_user_logged_in() )
        $wp_admin_bar->add_menu( array( 'title' => __( 'Log In' ), 'href' => wp_login_url() ) );

/*Here you can add your own menus*/
    }


}
add_action( 'admin_bar_menu', 'custom_login_adminbar' );
add_filter( 'show_admin_bar', '__return_true' , 1000 );


 

By default the admin bar will come with wordpress documentation link and search box. You can remove the admin bar items by using wp_before_admin_bar_render filter. Following code will remove the wordpress documentation link for non-logged-in user.

Just paste the following code in either plugin files or in the functions.php ( theme file ).

    if(!function_exists('custom_admin_bar_render')) {
        function custom_admin_bar_render() {


            if ( !is_user_logged_in() ) {
                global $wp_admin_bar;
                $wp_admin_bar->remove_menu('wp-logo');
            }


        }
    }
add_action( 'wp_before_admin_bar_render', 'custom_admin_bar_render' );

Tuesday, 7 May 2013

Adding Log in Log out link to menu

We can add the Log in / Log out link to the menu assigned to the particular Theme Location by using wp_nav_menu_items filter.

Just paste the following code in either plugin files or in the functions.php ( theme file ).

add_filter('wp_nav_menu_items', 'custom_add_login_logout_link', 10, 2);

if(!function_exists('custom_add_login_logout_link')){
    function custom_add_login_logout_link($items, $args) {  

 
        $menu_name = 'primary'; /*Here primary specifies the Theme Location in which your menu is assigned*/
            if ( ! is_user_logged_in() )
                $link = '<a href="' . esc_url( wp_login_url() ) . '">Log In</a>';
            else
                $link = '<a href="' . esc_url( wp_logout_url() ) . '">Log Out</a>';
       
        if ( ($menu_name) && ($args->theme_location == $menu_name) )
            $items .= '<li class="menu-item menu-item-type-post_type menu-item-object-page">'. $link .'</li>';
        return $items;
    }
}

Thursday, 18 April 2013

Blank search issue in wordpress

In wordpress default search form the blank search will redirects to home page. We can use request filter to the trick. Following code can be used to redirect the blank search to search page.

Just paste the following code in either plugin files or in the functions.php ( theme file ).

add_filter( 'request', 'blank_search_fix' );

if(!function_exists('blank_search_fix')){
 function blank_search_fix( $query_vars ) {
     if( isset( $_GET['s'] ) && empty( $_GET['s'] ) ) {
         $query_vars['s'] = " ";
     }
     return $query_vars;
 }
}

in this code $_GET['s'] denotes the search field in the (search)form  
<input type="text" name="s" id="s" value="<?php echo trim( get_search_query() ); ?>" />


Thursday, 14 March 2013

Renaming Admin menu

Renaming the admin menu/submenu items is simple by using admin_head filter. Not only that, we can also change the Link of the menu/submenu items.

Consider the sample code to renaming the Labels. Just paste the following code in either plugin files or in the functions.php ( theme file ).

if(!function_exists('custom_admin_menu_labelrename')){

    function custom_admin_menu_labelrename(){

        global $submenu, $menu;

        /* we can get index of the menu by using this code print_r($menu);/print_r($submenu)*/

        $menu[2][0] = 'Overview'; /*Here I just changed the Dashboard label to Overview*/        

        $submenu['index.php'][0][2] = 'http://examplesite.com';/* Custom link to Home (submenu of Dashboard Menu) menu*/

        $submenu['index.php'][0][0] = 'My Home'; /*Home (submenu of Dashboard Menu)label to My Home*/       
       
    }
}

add_filter( 'admin_head', 'custom_admin_menu_labelrename' );

Friday, 1 March 2013

Custom arguments to add_filter

We can pass custom arguments to filters when using add_filter.

For example plugin needs to pass the order dynamically it can be done by using global variables.Sample code to change the order by using posts_orderby_request filter
.

global $corder;
$corder = 'asc';
add_filter( 'posts_orderby_request',function(){ 
                  global $corder; 
                  $val = " wp_posts.post_title $corder";
                  return $val;
                }
          );

Wednesday, 27 February 2013

Reorder Admin submenus

We can  reorder the WordPress admin sub menus without changing the code in core by  using custom_menu_order filter.


Sample code to change the order of Dashboard Sub Menus.Just paste the following code in either plugin files or in the functions.php ( theme file )

add_filter( 'custom_menu_order', 'custom_admin_submenu_order' );

if(!function_exists('
custom_admin_submenu_order')){
    function
custom_admin_submenu_order( $menu_ord )
    {
        global $submenu;


        $arr = array();

        /*The values 10 and 0 are the index of the submenus Updates and Home. "index.php" is the array index of the Dashboard menu It can be Fetched by using print_r($submenu) */

        $
submenu_re_index = array(10,0);
        foreach($
submenu_re_index as $re_index){
            $arr[] = $submenu['index.php'][$
re_index];
        }
       
        $submenu['index.php'] = $arr;

        return $menu_ord;
    }
}


We can also remove the sub items by simply not specifying the index of the sub menu.