Append USER ID to an outbound link?

You should be able to use get_current_user_id(). Note that it will return ‘0’ if the user isn’t logged in.

<a href="https://example.com/?user_id=<?php echo get_current_user_id(); ?>">Link</a>


Update 2: Got bored, made a plugin: https://github.com/AndyMardell/append-user-id/releases/tag/v1.0.0-alpha

Download the zip and install 🙂 Submitted to WordPress but it’s still under review.

Installation and Usage: https://github.com/AndyMardell/append-user-id#installation


Update: you won’t be able to do this without PHP. But hear me out…

1) Add the following PHP to your theme’s functions.php file:

function prefix_get_current_user_id( $atts, $content, $tag ) {
    $atts        = array_change_key_case( (array) $atts, CASE_LOWER );
    $prefix_atts = shortcode_atts(
        array( 'url' => '' ),
        $atts,
        $tag
    );

    if ( is_user_logged_in() ) {
        $a_open = sprintf(
            '<a href="https://wordpress.stackexchange.com/questions/356065/%s?user_id=%s">',
            esc_url( $prefix_atts['url'] ),
            get_current_user_id()
        );
        return $a_open . esc_html( $content ) . '</a>';
    }

    $a_open = sprintf(
        '<a href="%s">',
        esc_url( $prefix_atts['url'] )
    );

    return $a_open . esc_html( $content ) . '</a>';
}

function prefix_add_shortcodes() {
    add_shortcode( 'link_with_id', 'prefix_get_current_user_id' );
}
add_action( 'init', 'prefix_add_shortcodes' );

2) Edit your post/page content and add the following shortcode:

[link_with_id url="https://domain.com/link"]A link to a page[/link_with_id]

This will output the following html:

<a href="https://domain.com/link?user_id=1">A link to a page</a>

or if the user isn’t logged in, it will output:

<a href="https://domain.com/link">A link to a page</a>

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)