Pages

Saturday, 22 November 2014

50 Filtering the Script Loader Source of WordPress

Let's begin!

WordPress has its own script loader, wp_enqueue_script(), which allows us to "queue" JavaScript files and not hard-code them. And this little filter calledscript_loader_src lets us how the scripts will be queued and outputted.

Google Page Speed, Yahoo YSlow and other website performance measurement tools usually hate URL parameters in JavaScript files. And they're right, too: Scripts with parameters at the end of their URLs don't get cached by "proxy servers" (more info on this topic here) and sadly, WordPress enables "version" parameters for scripts (and styles, too) by default. Luckily, we can simply remove those verparameters with a few lines of code:
01
02
03
04
05
06
07
08
09
10
11
12
13
<?php
 
function script_loader_src_example( $src ) {
    return remove_query_arg( 'ver', $src );
}
 
add_filter( 'script_loader_src', 'script_loader_src_example' );
// Tiny bonus: You can do it with styles, too!
add_filter( 'style_loader_src', 'script_loader_src_example' );
 
 
?>
Done! Your JavaScript (and CSS) files will not have any version parameters anymore.
If you want to learn more about proper JavaScript usage with WordPress, be sure tocheck out my article on this topic.
The admin_post_thumbnail_html filter, as its name suggests, allows you to add HTML content inside the "Featured Image" metabox. The HTML will appear right below the "Set featured image" link.
Imagine that you're making a personal blog for your client, but he insisted on maintaining the blog on his own instead of hiring an assistant. He always forgets how to add a featured image (He calls it "top image".) and you need to leave a reminder on the New Post page. Here's how you do it:
01
02
03
04
05
06
07
08
09
10
<?php
 
add_filter( 'admin_post_thumbnail_html', 'admin_post_thumbnail_html_example' );
 
function admin_post_thumbnail_html_example( $html ) {
    return $html .= '<p>Hi Mr. Smith! Click above to add an image to be displayed at the top of your post. Remember: <strong>The width of the image should be at least 900px</strong>!</p>';
 
}
 
?>
With your helpful reminder, your client will never forget to set a "top image" with a minimum width of 900 pixels.
By default, WordPress prevents "comment flooders" who repeatedly comments on your posts. For example, if a visitor posts a comment to a post in your website, they must wait 15 seconds (default value) before posting another comment. This filter lets you change the time setting to another value – or disable flood checking altogether.
As I said, WordPress makes visitors wait for 15 seconds before posting another comment. In some scenarios, you might need to increase this time limit to, say, 60 seconds. Here's how you do it:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
<?php
 
add_filter( 'comment_flood_filter', 'comment_flood_filter_example', 10, 3 );
 
function comment_flood_filter_example( $flood_control, $time_last, $time_new ) {
    $seconds = 60;
    if ( ( $time_new - $time_last ) < $seconds )
        return true;
    return false;
}
 
 
?>
Change the value "60" above to anything you want.
If you don't care about visitors speed-commenting, you can disable checking for flooding by using the two simple lines below:
1
2
3
4
5
6
<?php
 
remove_all_filters( 'comment_flood_filter' );
add_filter( 'comment_flood_filter', '__return_false', 10, 3 );
 
?>
Notice the remove_all_filters() function? As its name suggests, it removes all filtering functions from a filter hook.
The "At a Glance" section (formerly named "Right Now") keeps us up to date about how many posts, pages and comments are there in the database of your website. The dashboard_glance_items filter helps us show additional information there, like the number of posts of a custom post type.
Let's imagine that you have an "event blog" where you keep your visitors informed by new local events which you post as a custom post type named "Events" (and with the id event). To be able to see the count of events in your blog, you can use the function below and hook it to the dashboard_glance_items filter like so:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
 
add_filter( 'dashboard_glance_items', 'dashboard_glance_items_example' );
 
function dashboard_glance_items_example( $items = array() ) {
    $post_types = array( 'event' );
    foreach( $post_types as $type ) {
        if( ! post_type_exists( $type ) ) continue;
        $num_posts = wp_count_posts( $type );
        if( $num_posts ) {
            $published = intval( $num_posts->publish );
            $post_type = get_post_type_object( $type );
            $text = _n( '%s ' . $post_type->labels->singular_name, '%s ' . $post_type->labels->name, $published, 'your_textdomain' );
            $text = sprintf( $text, number_format_i18n( $published ) );
            if ( current_user_can( $post_type->cap->edit_posts ) ) {
            $output = '<a href="edit.php?post_type=' . $post_type->name . '">' . $text . '</a>';
                echo '<li class="post-count ' . $post_type->name . '-count">' . $output . '</li>';
            } else {
            $output = '<span>' . $text . '</span>';
                echo '<li class="post-count ' . $post_type->name . '-count">' . $output . '</li>';
            }
        }
    }
    return $items;
}
 
 
?>
Easy, right? Change the value of the $post_types variable (array) to suit your needs.
The login_message filter allows us to edit default messages that's outputted right above the login forms of our WordPress installations. (Not "errors", just neutral messages.)
If you ever need to simplify the default "lost password" instructions ("Please enter your username or email address. You will receive a link to create a new password via email."), you can change it like so:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
<?php
 
add_filter( 'login_message', 'login_message_example' );
 
function login_message_example( $message ) {
    $action = $_REQUEST['action'];
    if( $action == 'lostpassword' ) {
        $message = '<p class="message">Enter your email address, then check your inbox for the "reset password" link!</p>';
        return $message;
    }
    return;
}
 
 
?>
There are a number of actions that can be found in the wp-login.php file:
  • logout
  • lostpassword and retreivepassword (alias)
  • resetpass and rp (alias)
  • register
  • login
Just like the one we did in the example, you can write different messages for different action.
There are messages displayed when you update, trash, untrash, or delete posts. If you want to edit those messages, the bulk_post_updated_messages is your guy.
Let's say you don't like the way those messages are displayed for bulk actions of your custom post type "event" and you want to change them. Here's how you do it:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
<?php
 
add_filter( 'bulk_post_updated_messages', 'bulk_post_updated_messages_example', 10, 2 );
 
function bulk_post_updated_messages_example( $bulk_messages, $bulk_counts ) {
    $bulk_messages['event'] = array(
        'updated'   => _n( '%s event updated.', '%s events updated.', $bulk_counts['updated'] ),
        'locked'    => _n( '%s event not updated, somebody is editing it.', '%s events not updated, somebody is editing them.', $bulk_counts['locked'] ),
        'deleted'   => _n( '%s event permanently deleted.', '%s events permanently deleted.', $bulk_counts['deleted'] ),
        'trashed'   => _n( '%s event moved to the Trash.', '%s events moved to the Trash.', $bulk_counts['trashed'] ),
        'untrashed' => _n( '%s event restored from the Trash.', '%s events restored from the Trash.', $bulk_counts['untrashed'] ),
    );
 
    return $bulk_messages;
}
 
 
?>
Easy, right? Remember to make the strings translatable if you're not the only one to use the plugin or theme.
In some cases, you may need to tamper with the core Categories widget. With thewidget_categories_args filter, you can do that.
If you ever need to "hide" some categories in the Categories widget, use this code snippet:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
<?php
 
add_filter( 'widget_categories_args', 'widget_categories_args_example' );
 
function widget_categories_args_example( $cat_args ) {
    $exclude_arr = array( 4, 10 );
 
    if( isset( $cat_args['exclude'] ) && !empty( $cat_args['exclude'] ) )
        $exclude_arr = array_unique( array_merge( explode( ',', $cat_args['exclude'] ), $exclude_arr ) );
    $cat_args['exclude'] = implode( ',', $exclude_arr );
    return $cat_args;
}
 
 
?>
Change the $exclude_arr array items with the IDs of your "unwanted" categories and you're good to go.
By default, WordPress just reminds you to check your email after registration and doesn't redirect you anywhere. With the registration_redirect filter, however, you can set a custom safe address to redirect upon successful registrations.
If you offer a free e-book to your visitors if they sign up for your website, you can redirect them to the page with the download link of your e-book by using this simple code snippet:
01
02
03
04
05
06
07
08
09
10
11
<?php
 
add_filter( 'registration_redirect', 'registration_redirect_example' );
 
function registration_redirect_example() {
    return home_url( '/your-free-ebook/' );
}
 
 
?>
Remember, the redirection is done with the wp_safe_redirect() function which means that you can't redirect to an external site unless you used theallowed_redirect_hosts filter to specify external and "safe" hosts. We went through that filter in the first batch of these examples, be sure to read that tutorial if you haven't yet.
WordPress has the comment_form() function for displaying the comment form, and you can change its field by using the function's arguments. If you're developing a plugin, however, you won't be able to change any parameters of the function. This little filter allows us to change the HTML code of the default form fields – or remove them.
Let's say you, as a freelance web designer, are making a "default adjustments plugin" for all your clients and for security purposes, you want to remove the URL fields in the comment forms of all your websites. You can add a really simple function (and hook it to a filter) to make it happen:
01
02
03
04
05
06
07
08
09
10
11
12
<?php
 
add_filter( 'comment_form_default_fields', 'comment_form_default_fields_example' );
 
function comment_form_default_fields_example( $fields ) {
    unset( $fields['url'] );
    return $fields;
}
 
 
?>
Paste this lines into your plugin file and you're done!
By default, you can upload a number of file types into WordPress' Media Library –check out the full list of file types here. With the help of the upload_mime filter, you can make changes with the list of allowed file types.

0 comments:

Post a Comment

Text