How to default all users to no link for attachments?

This is the final non-JS method that finally worked for me:

Step 1: update sitewide option

You can do this several ways. Since setting it is a one-time operation, I opted to update this by visiting https://www.example.com/wp-admin/options.php . I searched for “image_default_link_type” and set it to “none” (the word none, not null), then saved the settings.

Unfortunately, saved usermeta overrides this sitewide setting – so the problem links were continuing to appear at this point.

Step 2: update all users

Many thanks to @Milo for revealing the location this is stored under – usermeta, buried in a query string of options that may appear in any order.

In theory this could be a one-time operation, or if you think users may continually update their defaults, you can set this to run on a hook like wp_dashboard_setup so every time someone views the dashboard, all users’ “urlbutton” options are removed, which causes the site to use the sitewide “image_default_link_type”. I opted to go with run-on-dashboard-view.

add_action('wp_dashboard_setup', 'wpse_update_user_defaults');
function wpse_update_user_defaults() {
    $users = get_users();
    foreach($users as $user) {
        // pull current settings
        $wpUserSettings = get_user_meta($user->ID, 'wp_user-settings', true);   
        // if 'wp_user-settings' is present with a 'urlbutton' value
        if(!empty($wpUserSettings) && strpos($wpUserSettings, 'urlbutton') !== false) {
            // if 'urlbutton' is not the only setting
            if(strpos((string)$wpUserSettings, '&') !== false) {
                // if there's an & before (may or may not have an & after)
                $firstUpdate = preg_replace("/&urlbutton=[^&]*/", '', $wpUserSettings);
                // if there's an & after (but not before)
                $secondUpdate = preg_replace("/^urlbutton=[^&]*&/", '', $firstUpdate);
                // save updated meta
                update_user_meta($user->ID, 'wp_user-settings', $secondUpdate);
            // if 'urlbutton' is the only setting
            } else {
                delete_user_meta($user->ID, 'wp_user-settings');
            }
        }
    }
}

After I got this sorted out, I searched for existing posts with the problem by using this query:

SELECT * FROM wp_posts WHERE post_content LIKE "%rel=\"attachment%"

and from there edited all the posts manually to remove the tags.

Leave a Comment