Show diffrent button depending on the User role

I just finished building this code using Gemini. This is for TaskHive

The following code will hide the “Post Request” button or “List a Service” option depending on whether the user is a Subscriber (client) or a Contributor (vendor). If the user is not logged in, the buttons will disappear. However, if the user is an Admin, they will be able to see both buttons.

Paste the below code into your Child Theme’s Functions.php file.

Enjoy!

<?php
/**
 * Conditionally hide header buttons based on user role using wp_head.
 * This version uses a more robust method to build and echo the CSS.
 */
function hivepress_child_hide_header_buttons() {
    $css = '';

    // For non-logged-in users, hide both buttons.
    if ( ! is_user_logged_in() ) {
        $css .= '
            .hp-menu__item--listing-submit,
            .hp-menu__item--request-submit {
                display: none !important;
            }
        ';
    } else {
        $user = wp_get_current_user();
        $roles = ( array ) $user->roles;

        // If the user is an administrator, do nothing and show all buttons.
        if ( in_array( 'administrator', $roles ) ) {
            return;
        }

        // For Subscribers, hide "List a Service" button.
        if ( in_array( 'subscriber', $roles ) ) {
            $css .= '
                .hp-menu__item--listing-submit {
                    display: none !important;
                }
            ';
        }

        // For Contributors, hide "Post a Request" button.
        if ( in_array( 'contributor', $roles ) ) {
            $css .= '
                .hp-menu__item--request-submit {
                    display: none !important;
                }
            ';
        }
    }

    // Only output the style block if there is CSS to apply.
    if ( ! empty( $css ) ) {
        echo '<style type="text/css">' . $css . '</style>';
    }
}
add_action( 'wp_head', 'hivepress_child_hide_header_buttons' );

2 Likes

Hi,

Thank you for the solution! This will be very helpful for our community.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.