WordPress Plugin: Pocket Read It Later Links

Latest version: 1.0– Released 15/06/2012:

  • Initial release.

Description

This plugin allows you to display Pocket ‘Read It Later’ links next to each post on your blog. You can see an example on the Pocket blog. You can automatically insert the links adjacent to your blog posts or you can use the template tag to insert the links wherever you like.

Continue reading “WordPress Plugin: Pocket Read It Later Links”

Saving Post Meta Field Revisions in WordPress

If your plugin or theme uses custom post meta fields then you may want to store revisions to these fields when a post revision is saved. It’s easy to do.

For each of our meta fields, we’ll need to do three things:

  1. Store a revision of the meta field when a post is saved
  2. Revert to the correct revision of the meta field when a post is reverted
  3. Optionally, display the meta field on the revisions screen

Continue reading “Saving Post Meta Field Revisions in WordPress”

Access Your Desktop Development Environment from Your Mobile Device

It’s possible to get an iPhone, iPad, or Android device to access a local web server running on your development machine. All you need is an HTTP proxy such as Charles Proxy running on your development machine. Once that’s running:

Make sure your device is connected to the same network as your development machine. Go into the Settings -> Wi-Fi menu and find the HTTP proxy settings. On Android, this means a long-press on your Wi-Fi network (Modify Settings, then Show advanced settings). On iOS this means pressing the (i) icon next to your Wi-Fi network.

Switch your proxy over to ‘Manual’ and enter your development environment machine’s network IP address (eg. 192.168.0.4) as the server, and 8888 as the port (Charles’ default port unless you’ve changed it).

Voila. All your HTTP traffic from your device will now route through your host machine (Charles will prompt you to allow access first) and you’ll have access to your local development server. Awesome!

Pro Tip: Are you still editing your hosts file in order to manage the host name mapping for sites on your development environment? Stop it. Just use the Tools -> DNS Spoofing menu in Charles and make life easier for yourself.

Basic Authentication with the WordPress HTTP API

Basic Authentication (or BasicAuth) is not natively handled with the WordPress HTTP API. This means when you’re using functions such as wp_remote_get() and wp_remote_post() there’s no immediately obvious way to send Basic Authentication headers with your request. It would be great to pass username and password parameters to these functions, but it’s not there.

Fear not though, it’s really easy. Here’s how:

$args = array(
  'headers' => array(
    'Authorization' => 'Basic ' . base64_encode( YOUR_USERNAME . ':' . YOUR_PASSWORD )
  )
);
wp_remote_request( $url, $args );

That’s it. The correct authentication headers will then be sent with your request (after you’ve replaced YOUR_USERNAME and YOUR_PASSWORD with the obvious).

I’d like to give a quick shout out to my favourite HTTP monitor Charles Proxy. I use Charles almost daily when dealing with server-side HTTP requests and AJAX requests and it makes life much easier. I love it.

WordPress Plugin: Feed Thumbnails

Latest version: 1.2– Released 04/07/2010
  • Bugfix for the Get The Image plugin integration.

Description

This plugin simply adds your post thumbnails to your feed as RSS enclosures. Nothing else to it. If you don’t use thumbnails or you don’t know what enclosures are or why you might want them, then this probably isn’t for you.

The plugin supports the Post Thumbnail feature built into WordPress and the Get The Image plugin by Justin Tadlock.

Installation

  1. Unzip the ZIP file and drop the folder straight into your wp-content/plugins/ directory.
  2. Activate the plugin through the ‘Plugins’ menu in WordPress.
  3. View your feed (you might need to do a hard refresh – ctrl+reload) and any posts that have a thumbnail defined will have an enclosure containing a link to the thumbnail.

Download

This plugin requires WordPress version 2.9 or later.

Version 1.2 ZIP file from downloads.wordpress.org

Any comments, questions, queries, suggestions, complaints, etc, please leave a comment!

Twitter Bookmarklet: View the Whole Conversation

Update: For those who aren’t aware, when Twitter was originally launched it had no concept of replies, threading, or viewing conversations. The functionality below was written in this era and now, of course, it’s redundant and no longer works.

Do you ever view a Twitter update (or a “tweet”) which is part of a conversation and wish there was an easy way to view the entire conversation?

It’s not easy to do. (We’re talking about the web interface here, it’s undoubtedly easy for those who use Twitter clients.) This is why I’ve written the Twitter Conversation Bookmarklet.

Installation

Drag the following link to your browser’s Bookmarks Toolbar:

[twitter conversation]

Usage

Simply press the bookmarklet whenever you’re on a Twitter status page that is part of a conversation, and the entire conversation will be magically loaded onto the page.

Example

The best way to see an example is just to install the bookmarklet and then hit it on a status page. An example status where it works well is this recent tweet by Damien Mulley which is part of a conversation.

Results of the Twitter conversation bookmarklet

Known Issues

  • Currently, the bookmarklet won’t return a conversation if you use it on the first tweet that is part of a conversation. It must be used on a tweet that is replying to another. This appears to be a limitation of the Twitter API but I am looking into ways to work around this.

Comments and bug reports appreciated.

WordPress Plugin: Logout Password Protected Posts

Latest version: 0.2 – Released 19 April 2020

Description

There is no built-in way for your visitors to “log out” of password protected posts once they’ve entered the password. Even logged in users cannot log out of password protected posts by logging out of their account. This plugin solves that problem by providing a link for your visitors to log out of password protected posts.

Setup

After installing the plugin, add the following code somewhere in your theme to display a link for logging out of password protected posts:

<?php do_action( 'posts_logout_link' ); ?>

Installation

FAQ

I can’t see a link to log out. What’s up?

Have you added the template tag somewhere in your theme? You need to add <?php do_action( 'posts_logout_link' ); ?> somewhere in your theme for the link to show up.

I’ve added the template tag to my theme but I can’t see the log out link. What’s up?

Ensure that you have entered a password for a password protected post. The link will not show up if you’re not logged into a password protected post.

Can I change the default text in the link?

Sure. Add a second parameter to the template tag with the text you’d like instead. For example: <?php do_action( 'posts_logout_link', 'Log out!' ); ?>

For those who want even more control, you can also add a third paramter which will be used as the class name on the link element.

Download

Version 0.2 ZIP file from downloads.wordpress.org

Any comments, questions, queries, suggestions, complaints, etc, please leave a comment!

WordPress Plugin: User Switching

Latest version: 1.5.8– Released 25 January 2022:

Description

This plugin allows you to quickly swap between user accounts in WordPress at the click of a button. You’ll be instantly logged out and logged in as your desired user. This is handy for test environments where you regularly log out and in between different accounts, or for administrators who need to switch between multiple accounts.

Features

  • Switch user: Instantly switch to any user account from the Users screen.
  • Switch back: Instantly switch back to your originating account.
  • Switch off: Log out of your account but retain the ability to instantly switch back in again.
  • Switching between users is secure (see the Security section below).
  • Compatible with WordPress, WordPress Multisite, WooCommerce, BuddyPress, bbPress, and most two-factor authentication plugins.

Security

  • Only users with the ability to edit other users can switch user accounts. By default this is only Administrators on single site installations, and Super Admins on Multisite installations.
  • Passwords are not (and cannot be) revealed.
  • Uses the cookie authentication system in WordPress when remembering the account(s) you’ve switched from and when switching back.
  • Implements the nonce security system in WordPress, meaning only those who intend to switch users can switch.
  • Full support for user session validation where appropriate.
  • Full support for administration over SSL (if applicable).

Usage

  1. Visit the Users menu in WordPress and you’ll see a Switch To link in the list of action links for each user.
  2. Click this and you will immediately switch into that user account.
  3. You can switch back to your originating account via the Switch back link on each dashboard screen or in your profile menu in the WordPress toolbar.

See the FAQ for information about the Switch Off feature.

Other Plugins

I maintain several other plugins for developers. Check them out:

  • Query Monitor is the developer tools panel for WordPress
  • WP Crontrol lets you view and control what’s happening in the WP-Cron system

Privacy Statement

User Switching makes use of browser cookies in order to allow users to switch to another account. Its cookies operate using the same mechanism as the authentication cookies in WordPress core, therefore their values contain the user’s user_login field in plain text which should be treated as potentially personally identifiable information. The names of the cookies are:

  • wordpress_user_sw_{COOKIEHASH}
  • wordpress_user_sw_secure_{COOKIEHASH}
  • wordpress_user_sw_olduser_{COOKIEHASH}

User Switching does not send data to any third party, nor does it include any third party resources, nor will it ever do so.

See also the FAQ for some questions relating to privacy and safety when switching between users.

Ethical Open Source

User Switching is considered Ethical Open Source because it meets all of the criteria of The Ethical Source Definition (ESD):

  1. It benefits the commons.
  2. It is created in the open.
  3. Its community is welcoming and just.
  4. It puts accessibility first.
  5. It prioritizes user safety.
  6. It protects user privacy.
  7. It encourages fair compensation.

FAQ

Does this plugin work with PHP 8?

Yes.

What does “Switch off” mean?

Switching off logs you out of your account but retains your user ID in an authentication cookie so you can switch straight back without having to log in again manually. It’s akin to switching to no user, and being able to switch back.

The Switch Off link can be found in your profile menu in the WordPress toolbar. Once you’ve switched off you’ll see a Switch back link on the Log In screen and in the footer of your site.

Does this plugin work with WordPress Multisite?

Yes, and you’ll also be able to switch users from the Users screen in Network Admin.

Does this plugin work with BuddyPress?

Yes, and you’ll also be able to switch users from member profile screens and the member listing screen.

Does this plugin work with bbPress?

Yes, and you’ll also be able to switch users from member profile screens.

Does this plugin work with WooCommerce?

Yes. For maximum compatibility you should use WooCommerce version 3.6 or later.

Does this plugin work if my site is using a two-factor authentication plugin?

Yes, mostly.

One exception I’m aware of is Duo Security. If you’re using this plugin, you should install the User Switching for Duo Security add-on plugin which will prevent the two-factor authentication prompt from appearing when you switch between users.

What capability does a user need in order to switch accounts?

A user needs the edit_users capability in order to switch user accounts. By default only Administrators have this capability, and with Multisite enabled only Super Admins have this capability.

Can the ability to switch accounts be granted to other users or roles?

Yes. The switch_users meta capability can be explicitly granted to a user or a role to allow them to switch users regardless of whether or not they have the edit_users capability. For practical purposes, the user or role will also need the list_users capability so they can access the Users menu in the WordPress admin area.

Can the ability to switch accounts be denied from users?

Yes. User capabilities in WordPress can be set to false to deny them from a user. Denying the switch_users capability prevents the user from switching users, even if they have the edit_users capability.

add_filter( 'user_has_cap', function( $allcaps, $caps, $args, $user ) {
    if ( 'switch_to_user' === $args[0] ) {
        if ( my_condition() ) {
            $allcaps['switch_users'] = false;
        }
    }
    return $allcaps;
}, 9, 4 );

Note that this needs to happen before User Switching’s own capability filtering, hence the priority of 9.

Can I add a custom “Switch To” link to my own plugin or theme?

Yes. Use the user_switching::maybe_switch_url() method for this. It takes care of authentication and returns a nonce-protected URL for the current user to switch into the provided user account.

if ( method_exists( 'user_switching', 'maybe_switch_url' ) ) {
    $url = user_switching::maybe_switch_url( $target_user );
    if ( $url ) {
        printf(
            '<a href="%1$s">Switch to %2$s</a>',
            esc_url( $url ),
            esc_html( $target_user->display_name )
        );
    }
}

This link also works for switching back to the original user, but if you want an explicit link for this you can use the following code:

if ( method_exists( 'user_switching', 'get_old_user' ) ) {
    $old_user = user_switching::get_old_user();
    if ( $old_user ) {
        printf(
            '<a href="%1$s">Switch back to %2$s</a>',
            esc_url( user_switching::switch_back_url( $old_user ) ),
            esc_html( $old_user->display_name )
        );
    }
}

Can I determine whether the current user switched into their account?

Yes. Use the current_user_switched() function for this.

if ( function_exists( 'current_user_switched' ) ) {
    $switched_user = current_user_switched();
    if ( $switched_user ) {
        // User is logged in and has switched into their account.
        // $switched_user is the WP_User object for their originating user.
    }
}

Does this plugin allow a user to frame another user for an action?

Potentially yes, but User Switching includes some safety protections for this and there are further precautions you can take as a site administrator:

  • User Switching stores the ID of the originating user in the new session for the user they switch to. Although this session does not persist by default when they subsequently switch back, there will be a record of this ID if your MySQL server has query logging enabled.
  • User Switching stores the login name of the originating user in an authentication cookie (see the Privacy Statement for more information). If your server access logs store cookie data, there will be a record of this login name (along with the IP address) for each access request.
  • You can install an audit trail plugin such as Simple History, WP Activity Log, or Stream, all of which have built-in support for User Switching and all of which log an entry when a user switches into another account.
  • User Switching triggers an action when a user switches account, switches off, or switches back (see below). You can use these actions to perform additional logging for safety purposes depending on your requirements.

One or more of the above should allow you to correlate an action with the originating user when a user switches account, should you need to.

Bear in mind that even without the User Switching plugin in use, any user who has the ability to edit another user can still frame another user for an action by, for example, changing their password and manually logging into that account. If you are concerned about users abusing others, you should take great care when granting users administrative rights.

Can regular admins on Multisite installations switch accounts?

No. This can be enabled though by installing the User Switching for Regular Admins plugin.

Can I switch users directly from the admin toolbar?

Yes, there’s a third party add-on plugin for this: Admin Bar User Switching.

Are any plugin actions called when a user switches account?

Yes. When a user switches to another account, the switch_to_user hook is called:

/**
 * Fires when a user switches to another user account.
 *
 * @since 0.6.0
 * @since 1.4.0 The `$new_token` and `$old_token` parameters were added.
 *
 * @param int    $user_id     The ID of the user being switched to.
 * @param int    $old_user_id The ID of the user being switched from.
 * @param string $new_token   The token of the session of the user being switched to. Can be an empty string
 *                            or a token for a session that may or may not still be valid.
 * @param string $old_token   The token of the session of the user being switched from.
 */
do_action( 'switch_to_user', $user_id, $old_user_id, $new_token, $old_token );

When a user switches back to their originating account, the switch_back_user hook is called:

/**
 * Fires when a user switches back to their originating account.
 *
 * @since 0.6.0
 * @since 1.4.0 The `$new_token` and `$old_token` parameters were added.
 *
 * @param int       $user_id     The ID of the user being switched back to.
 * @param int|false $old_user_id The ID of the user being switched from, or false if the user is switching back
 *                               after having been switched off.
 * @param string    $new_token   The token of the session of the user being switched to. Can be an empty string
 *                               or a token for a session that may or may not still be valid.
 * @param string    $old_token   The token of the session of the user being switched from.
 */
do_action( 'switch_back_user', $user_id, $old_user_id, $new_token, $old_token );

When a user switches off, the switch_off_user hook is called:

/**
 * Fires when a user switches off.
 *
 * @since 0.6.0
 * @since 1.4.0 The `$old_token` parameter was added.
 *
 * @param int    $old_user_id The ID of the user switching off.
 * @param string $old_token   The token of the session of the user switching off.
 */
do_action( 'switch_off_user', $old_user_id, $old_token );

In addition, User Switching respects the following filters from WordPress core when appropriate:

  • login_redirect when switching to another user.
  • logout_redirect when switching off.

Do you accept donations?

I am accepting sponsorships via the GitHub Sponsors program and any support you can give will help me maintain this plugin and keep it free for everyone.

Download

This plugin requires WordPress version 3.7 or later.

Download the plugin on WordPress.org. Any comments, questions, queries, suggestions, complaints, etc, please leave a comment!