Search code examples
wordpressshortcodegravity-forms-plugincustom-wordpress-pages

is it possible to customize shortcode in theme -or- make new shortcode combining two shortcodes


I'm sorry if i asking stupid question because as i not code /php expert ?

I usering gravityview to filter and display gravity from values.

[gravityview id="111" search_field="11" search_value="xyzes"]

Now I want to change search_value dynamically AS "current logged in user"

So I trying making new SHORTCODE but not good working or not good idea

add_shortcode( 'customcode' , 'wp_get_current_user_func' );

function wp_get_current_user_func( $atts ) { 
    $current_user = wp_get_current_user();

    return do_shortcode('[gravityview id="1111" search_field="16" search_value="$current_user = wp_get_current_user();"]');
}

MY Request please suggest me what right code or is there any way in backend I able to do as altering theme file?

Thank you so much in advance


Solution

  • You were close enough. Here is how you should do it:

    add_shortcode( 'customcode' , 'wp_get_current_user_func' );
    
    function wp_get_current_user_func( $atts ) { 
    $current_user = wp_get_current_user();
    $user_login = $current_user->user_login;
    //return do_shortcode('[gravityview id="1111" search_field="16" search_value=".$user_login."]');
    $shortcode = sprintf(
    '[gravityview id="%1$s" search_field="%2$s" search_value="%3$s"]',
    "1111",
    "16",
    $user_login
    );
    echo do_shortcode( $shortcode );
    }
    

    You were missing to retrieve $current_user->user_login from function wp_get_current_user()

    $user_login = $current_user->user_login;
    

    You can also print out the other values as in this example:

    <?php
        $current_user = wp_get_current_user();
        /**
         * @example Safe usage: $current_user = wp_get_current_user();
         * if ( !($current_user instanceof WP_User) )
         *     return;
         */
        echo 'Username: ' . $current_user->user_login . '<br />';
        echo 'User email: ' . $current_user->user_email . '<br />';
        echo 'User first name: ' . $current_user->user_firstname . '<br />';
        echo 'User last name: ' . $current_user->user_lastname . '<br />';
        echo 'User display name: ' . $current_user->display_name . '<br />';
        echo 'User ID: ' . $current_user->ID . '<br />';
    ?>