0

I found a great solution for this issue in this article: How to add wordpress username after url?

/*
Plugin Name: My Awesome Button
Description: The shortcode [my-awesome-button] will be replaced with the HTML code for a button for logged-in users and for guests it will be replaced with an empty string (so it will be removed). This will work for posts and pages.
Author: Nikolay Nikolov
Version: 1.0.0
*/

add_filter( 'the_content', 'my_awesome_button_function', 99999999999 );

function my_awesome_button_function( $content ) {
    if ( strpos( $content, '[my-awesome-button]' ) !== false ) {
        if ( is_user_logged_in() ) {
            $current_user = wp_get_current_user();
            $button_html = '<a href="https://direktoriku.com/shopping/?user=' . esc_attr( $current_user->user_login ) . '"><button>Click me</button></a>';
            $content = str_replace( '[my-awesome-button]', $button_html, $content );
        } else {
            $content = str_replace( '[my-awesome-button]', '', $content );
        }
    }
    return $content;
}

My only problem, that the button is active only on the homepage and inactive on all of the other pages on the website (for example mydomain.com/documents).

Please be so kind and help me to fix it.

Thank you very much!

2
  • 2
    That button will be shown on those pages only where you put the shortcode. [my-awesome-button]. Try by adding this shortcode on another page content and check it. Jun 5 '20 at 14:35
  • And you might as well implement this using add_shortcode() not a content_filter if you're going to specify the button in shortcode syntax.
    – Rup
    Jun 5 '20 at 14:41
0

You can try this shortode in this plugin file or you can paste this method to bottom of active theme's functions.php. If you are new to WordPress and need a help you can visit here for steps to add code in function.

add_shortcode( 'my-awesome-button', 'wp_my_awesome_bytton' );
function wp_my_awesome_bytton( $atts ) {
    $button_html = '';
    if ( is_user_logged_in() ) {
            $current_user = wp_get_current_user();
            $button_html = '<a href="https://direktoriku.com/shopping/?user=' . esc_attr( $current_user->user_login ) . '"><button>Click me</button></a>';

    }
    return $button_html; 
}

// Use this shortcode anywhere in page/post content like this: [my-awesome-button] it will replace your shortcode to html code. More information about shortcode visit here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.