Generating a WordPress plugin activation link url

As I might need it again I’ve put together a gist for a WordPress function that will generate a plugin activation url like the ones WordPress will generate in the plugins administration screen

Activate link

The function will require a string input like my-plugin/my-plugin.php which can be hard-coded knowing a specific plugin folder and main plugin file information or using another function that will check for an installed plugin using its title.

 * Generate an activation URL for a plugin like the ones found in WordPress plugin administration screen.
 * @param  string $plugin A plugin-folder/plugin-main-file.php path (e.g. "my-plugin/my-plugin.php")
 * @return string         The plugin activation url
function generatePluginActivationLinkUrl($plugin)
    // the plugin might be located in the plugin folder directly

    if (strpos($plugin, '/')) {
        $plugin = str_replace('/', '%2F', $plugin);

    $activateUrl = sprintf(admin_url('plugins.php?action=activate&plugin=%s&plugin_status=all&paged=1&s'), $plugin);

    // change the plugin request to the plugin to pass the nonce check
    $_REQUEST['plugin'] = $plugin;
    $activateUrl = wp_nonce_url($activateUrl, 'activate-plugin_' . $plugin);

    return $activateUrl;


How to replace post name slug with post ID in Custom Post Types

Here is a way to replace the post slug with the post ID in a custom post type permalink structure.




Assuming the post type already exists with

'rewrite' => array('slug' => 'book') ...
 * Add new rewrite for post type
 * Add permalink structure
function book_post_type_rewrite() {
    global $wp_rewrite;
    // Set the query arguments used by WordPress
    $queryarg = 'post_type=book&p=';
    // Concatenate %book_id% to $queryarg (eg.. &p=123)
    $wp_rewrite->add_rewrite_tag( '%book_id%', '([^/]+)', $queryarg );
    // Add the permalink structure
    $wp_rewrite->add_permastruct( 'book', '/book/%book_id%/', false );
add_action( 'init', 'book_post_type_rewrite' );
 * Replace permalink segment with post ID
function book_post_type_permalink( $post_link, $id = 0, $leavename ) {
    global $wp_rewrite;
    $post = get_post( $id );
    if ( is_wp_error( $post ) )
        return $post;
        // Get post permalink (should be something like /book/%book_id%/
        $newlink = $wp_rewrite->get_extra_permastruct( 'book' );
        // Replace %book_id% in permalink structure with actual post ID
        $newlink = str_replace( '%book_id%', $post->ID, $newlink );
        $newlink = home_url( user_trailingslashit( $newlink ) );
    return $newlink;
add_filter('post_type_link', 'book_post_type_permalink', 1, 3);

Refresh permalinks