WordPress.org

Support

Support » Plugins and Hacks » Hacks » Mxpress edit to change color of a specific user role name and message

Mxpress edit to change color of a specific user role name and message

  • Hi im using the mxpress plugin and want to give each specific user role like Administrator, Editor etc. a diffent color for their name to display when they type a comment message.

    Ive manage to change the text color that display all messages in the functions_comment.php file

    <?php
    
    /**
     * Loads the comment template specified in $file.
     *
     * Will not display the comments template if not on single post or page, or if
     * the post does not have comments.
     *
     * Uses the WordPress database object to query for the comments. The comments
     * are passed through the 'comments_array' filter hook with the list of comments
     * and the post ID respectively.
     *
     * The $file path is passed through a filter hook called, 'comments_template'
     * which includes the TEMPLATEPATH and $file combined. Tries the $filtered path
     * first and if it fails it will require the default comment template from the
     * default theme. If either does not exist, then the WordPress process will be
     * halted. It is advised for that reason, that the default theme is not deleted.
     *
     * @since 1.5.0
     * @global array $comment List of comment objects for the current post
     * @uses $wpdb
     * @uses $post
     * @uses $withcomments Will not try to get the comments if the post has none.
     *
     * @param string $file Optional, default '/comments.php'. The file to load
     * @param bool $separate_comments Optional, whether to separate the comments by comment type. Default is false.
     * @return null Returns null if no comments appear
     */
    function mxpress_comments_template($file = '/comments.php', $separate_comments = false) {
        global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity, $overridden_cpage;
    
        if (!(is_single() || is_page() || $withcomments) || empty($post))
            return;
    
        if (empty($file))
            $file = '/comments.php';
    
        $req = false; //get_option('require_name_email');
        //mxpress_debug(array('$req', $req));
        /**
         * Comment author information fetched from the comment cookies.
         *
         * @uses wp_get_current_commenter()
         */
        $commenter = wp_get_current_commenter();
        //mxpress_debug(array('$commenter', $commenter));
    
        /**
         * The name of the current comment author escaped for use in attributes.
         */
        $comment_author = $commenter['comment_author']; // Escaped by sanitize_comment_cookies()
        //mxpress_debug(array('$comment_author', $comment_author));
        /**
         * The email address of the current comment author escaped for use in attributes.
         */
        $comment_author_email = $commenter['comment_author_email'];  // Escaped by sanitize_comment_cookies()
        //mxpress_debug(array('$comment_author_email', $comment_author_email));
        /**
         * The url of the current comment author escaped for use in attributes.
         */
        $comment_author_url = esc_url($commenter['comment_author_url']);
        //mxpress_debug(array('$comment_author_url', $comment_author_url));
        /** @todo Use API instead of SELECTs. */
        if ($user_ID) {
            $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) )  ORDER BY comment_date_gmt", $post->ID, $user_ID));
        } else if (empty($comment_author)) {
            $comments = get_comments(array('post_id' => $post->ID, 'status' => 'approve', 'order' => 'ASC'));
        } else {
            $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND ( comment_approved = '1' OR ( comment_author = %s AND comment_author_email = %s AND comment_approved = '0' ) ) ORDER BY comment_date_gmt", $post->ID, wp_specialchars_decode($comment_author, ENT_QUOTES), $comment_author_email));
        }
    
        // keep $comments for legacy's sake
        $wp_query->comments = apply_filters('comments_array', $comments, $post->ID);
        $comments = &$wp_query->comments;
        $wp_query->comment_count = count($wp_query->comments);
        update_comment_cache($wp_query->comments);
    
        if ($separate_comments) {
            $wp_query->comments_by_type = &separate_comments($comments);
            $comments_by_type = &$wp_query->comments_by_type;
        }
    
        $overridden_cpage = false;
        if ('' == get_query_var('cpage') && get_option('page_comments')) {
            set_query_var('cpage', 'newest' == get_option('default_comments_page') ? get_comment_pages_count() : 1 );
            $overridden_cpage = true;
        }
    
        if (!defined('COMMENTS_TEMPLATE') || !COMMENTS_TEMPLATE)
            define('COMMENTS_TEMPLATE', true);
    
        /* $include = apply_filters('comments_template', STYLESHEETPATH . $file );
          if ( file_exists( $include ) )
          require( $include );
          elseif ( file_exists( TEMPLATEPATH . $file ) )
          require( TEMPLATEPATH . $file );
          else // Backward compat code will be removed in a future release
          require( ABSPATH . WPINC . '/theme-compat/comments.php');
         */
    
        require 'mxpress_comments.php';
    }
    
    /**
     * Outputs a complete commenting form for use within a template.
     * Most strings and form fields may be controlled through the $args array passed
     * into the function, while you may also choose to use the comment_form_default_fields
     * filter to modify the array of default fields if you'd just like to add a new
     * one or remove a single field. All fields are also individually passed through
     * a filter of the form comment_form_field_$name where $name is the key used
     * in the array of fields.
     *
     * @since 3.0.0
     * @param array $args Options for strings, fields etc in the form
     * @param mixed $post_id Post ID to generate the form for, uses the current post if null
     * @return void
     */
    function mxpress_comment_form($args = array(), $post_id = null) {
        // modified clone of comment_form
        //mxpress_debug('mxpress_comment_form()');
        global $id;
    
        if (null === $post_id)
            $post_id = $id;
        else
            $id = $post_id;
    
        $commenter = wp_get_current_commenter();
        $user = wp_get_current_user();
        $user_identity = $user->exists() ? $user->display_name : '';
    
        $req = get_option('require_name_email');
        $aria_req = ( $req ? " aria-required='true'" : '' );
        $fields = array(
            'author' => '<p class="comment-form-author">' . '<label for="author">' . __('Name') . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) .
            '<input id="author" name="author" type="text" value="' . esc_attr($commenter['comment_author']) . '" size="30"' . $aria_req . ' /></p>',
            'email' => '<p class="comment-form-email"><label for="email">' . __('Email') . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) .
            '<input id="email" name="email" type="text" value="' . esc_attr($commenter['comment_author_email']) . '" size="30"' . $aria_req . ' /></p>',
            'url' => '<p class="comment-form-url"><label for="url">' . __('Website') . '</label>' .
            '<input id="url" name="url" type="text" value="' . esc_attr($commenter['comment_author_url']) . '" size="30" /></p>',
        );
    
        $required_text = sprintf(' ' . __('Required fields are marked %s'), '<span class="required">*</span>');
    
        $defaults = array(
            'fields' => apply_filters('comment_form_default_fields', $fields),
            'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x('Comment', 'noun') . '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea></p>',
            'must_log_in' => '<p class="must-log-in">' . sprintf(__('You must be <a href="%s">logged in</a> to post a comment.'), wp_login_url(apply_filters('the_permalink', get_permalink($post_id)))) . '</p>',
            'logged_in_as' => '<p class="logged-in-as">' . sprintf(__('Logged in as <a href="%1$s">%2$s</a>. <a href="%3$s" title="Log out of this account">Log out?</a>'), admin_url('profile.php'), $user_identity, wp_logout_url(apply_filters('the_permalink', get_permalink($post_id)))) . '</p>',
            'comment_notes_before' => '<p class="comment-notes">' . __('Your email address will not be published.') . ( $req ? $required_text : '' ) . '</p>',
            'comment_notes_after' => '<p class="form-allowed-tags">' . sprintf(__('You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: %s'), ' <code>' . allowed_tags() . '</code>') . '</p>',
            'id_form' => 'commentform',
            'id_submit' => 'submit',
            'title_reply' => __('Leave a Reply'),
            'title_reply_to' => __('Leave a Reply to %s'),
            'cancel_reply_link' => __('Cancel reply'),
            'label_submit' => __('Post Comment'),
        );
    
        $args = wp_parse_args($args, apply_filters('comment_form_defaults', $defaults));
        ?>
        <?php if (comments_open($post_id)) : ?>
            <?php do_action('comment_form_before'); ?>
            <div id="respond">
                <!-- h3 id="reply-title"><small><?php cancel_comment_reply_link($args['cancel_reply_link']); ?></small></h3 -->
                <?php $cancelurl = str_replace('&doMxpressComment=1', '', $_SERVER['REQUEST_URI']); ?>
                <a href="<?php echo $cancelurl; ?>">Cancel Comment</a><br><br>
                <?php /* if (get_option('comment_registration') && !is_user_logged_in()) : ?>
                  <?php echo $args['must_log_in']; ?>
                  <?php do_action('comment_form_must_log_in_after'); ?>
                  <?php else : */ ?>
                <form action="<?php echo site_url('/wp-comments-post.php'); ?>" method="post" id="<?php echo esc_attr($args['id_form']); ?>">
                    <?php //do_action('comment_form_top'); ?>
                    <?php
                    //if (is_user_logged_in()) :
                    // logged in users don't apply at the moment
                    /*          ?>
                      <?php echo apply_filters('comment_form_logged_in', $args['logged_in_as'], $commenter, $user_identity); ?>
                      <?php do_action('comment_form_logged_in_after', $commenter, $user_identity);
                     */
                    // else :
                    ?>
                    <?php // echo $args['comment_notes_before']; ?>
                    <?php
                    // do_action('comment_form_before_fields');
                    // mxpress_debug($args);
                    global $_SERVER;
                    //  mxpress_debug($_SERVER);
                    foreach ((array) $args['fields'] as $name => $field) {
                        //  echo '[' . apply_filters("comment_form_field_{$name}", $field) . "]\n";
                    }
                    global $_SERVER, $post;
                    $_mxpress_nic =  urldecode($_SERVER['HTTP_X_MXIT_NICK']);
                    $_mxpress_userid_r = $_SERVER['HTTP_X_MXIT_USERID_R'];
                    if ($_mxpress_nic == '') {
                        $_mxpress_nic = 'Unspecified Mxit User';
                    }
                    if ($_mxpress_userid_r == '') {
                        $_mxpress_userid_r = 'Unspecified.Mxit.User.ID';
                    }
                    echo 'Please write your comment now and click send:';
                    echo apply_filters('comment_form_field_comment', '<p class="comment-form-comment"><textarea id="comment" name="comment"  aria-required="true"></textarea></p>');
                    ?>
                    <input type="hidden" name="comment_post_ID" value="<?php echo $post->ID; ?>" />
                    <input type="hidden" name="author" value="<?php echo $_mxpress_nic; ?>" />
                    <input type="hidden" name="email" value="<?php echo $_mxpress_userid_r . '@mixit.im'; ?>" />
                    <input name="submit" type="submit" id="<?php echo esc_attr($args['id_submit']); ?>" value="<?php echo esc_attr($args['label_submit']); ?>" />
    
                    <?php //endif; ?>
    
                </form>
                <?php /* endif; */ ?>
            </div><!-- #respond -->
            <?php do_action('comment_form_after'); ?>
        <?php else : ?>
            <?php do_action('comment_form_comments_closed'); ?>
        <?php endif; ?>
        <?php
    }
    
    function mxpress_comment($comment, $args, $depth) {
        $GLOBALS['comment'] = $comment;
        //mxpress_debug(get_comment_text($comment_ID));
        extract($args, EXTR_SKIP);
    
        if ('div' == $args['style']) {
            $tag = 'div';
            $add_below = 'comment';
        } else {
            $tag = 'li';
            $add_below = 'div-comment';
        }
        ?>
        <<?php echo $tag ?> <?php comment_class(empty($args['has_children']) ? '' : 'parent') ?> id="comment-<?php comment_ID() ?>">
        <?php if ('div' != $args['style']) : ?>
            <div id="div-comment-<?php comment_ID() ?>" class="comment-body">
            <?php endif; ?>
    
            <?php //if ($args['avatar_size'] != 0) echo get_avatar($comment, $args['avatar_size']); ?>
            <?php echo '<span style="color:#63B8FF;">'. preg_replace("/[^A-Za-z0-9 ]/", '', urldecode(get_comment_author())).'</span><br/>'; ?>
    
            <?php if ($comment->comment_approved == '0') : ?>
                <em class="comment-awaiting-moderation"><?php _e('Your comment is awaiting moderation.') ?></em>
                <?php
            endif;
            //comment_text();
            echo $comment->comment_content;
    
            $now = new DateTime(date_i18n('Y-m-d H:i', time()));
            $ref = new DateTime(get_comment_date('Y-m-d') . ' ' . get_comment_time('H:i'));
            $diff = $now->diff($ref);
            echo ' <span style="color:#CCCCCC;"><i>(';
            if ($diff->d) {
                printf('%dd', $diff->d);
            } else {
                if ($diff->h) {
                    printf('%dh', $diff->h);
                } else {
                    printf('%dm', $diff->i);
                }
            }
             echo ' ago)</i></span>';
             // edit_comment_link(__('(Edit)'), '  ', '');
            ?>
    
            <?php //comment_reply_link(array_merge($args, array('add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
    
            <?php if ('div' != $args['style']) : ?>
            </div>
        <?php endif; ?>
        <?php
    }
    
    // send comments to oldest if neccesary
    function mxpress_cpage_intercept($query) {
        $mxpress_options = get_option('mxpress_options');
        $reverse_order = $mxpress_options['orderComments'];
        if ((mxpress_isMixit()) && ($reverse_order == 'False') && ($query->query_vars['cpage'] == NULL)) {
            $query->set('cpage', '1');
        }
    }
    ?>

    and my stylesheet looks like

    .mxblock {margin:0; padding:2em 0 0;}
    .mxpsection {display:block;margin:0; background: #CCC; padding:0}
    .mxpsection-detail {display:block;margin:0; background: #EEE; padding:0}
    .mxpsection-detail p {margin:0}
    .mxpsection h3{margin: 0; padding:0}
    .mxpsection h3 a{display:block;margin: 0; padding:0.5em ; }
    #mxpress_sections_menu{display:block; height: 3em; clear:both; }
    .mxptab{display:block;background:#eee; float:left; margin:0.25em;}
    .mxptab a{display:block;margin:0;padding:1em 0.25em 0;}
    .mxptab a:hover{background:#fff;}
    .mxspacer{margin:0}
    .doShow { display: inherit; }
    .doHide { display: none; }

    Can anyone help me out to change the font color of certain User ID roles or by username etc

    the mxpress can be found here and is being used as the theme aswell…

Viewing 15 replies - 1 through 15 (of 26 total)
  • Moderator bcworkz

    @bcworkz

    There’s endless variations really, here’s one. The actual comment is output by mxpress_comment(). For any HTML entity where you want the color to change, add the user’s role as a class. Depending on what class is already set, you would do something slightly different, but basically like this:
    <div class="existing_ class <?php cob_user_role( $comment->user_id ); ?>">

    Declare a function somewhere, such as functions.php because getting a user role is not super simple. You might also store the function’s return in a variable if it’s needed several times per comment instead of echoing it out directly.

    function cob_user_role( $user_id ) {
       $user = new WP_User( $user_id );
       echo $user->roles[0];
    }

    If any user has more than one role, this function is inadequate, only the first role is output, not necessarily the highest level.

    Finally, on a CSS page, define a color for each possible role:
    .author {color: #060;}
    Depending on what other color directives are applied to an entity, you may need a more specific selector and/or use !important to get the correct color applied.

    Hi im sorry but it doesnt work I triend implementing it but dont know how exactly it works…

    Moderator bcworkz

    @bcworkz

    My instructions are correct if properly implemented, I tested it on my site to be sure. Post the modified mxpress_comment() code and the CSS code based on role names so I can check for syntax or logic errors.

    Is the function declaration properly placed on functions.php? At the very bottom of the page usually works fine here.

    Are all of the role name CSS on styles.css? Not just author, you need subscriber, contributor, editor, administrator, etc.

    in which functions.php file should I fill it in because I cant find a line. Ive got the following different types of functions.php documents

    mxpress/template_static_front_page.php
    mxpress/template_page.php
    mxpress/functions_comments.php
    mxpress/functions_tracking.php
    mxpress/mxpress_footer.php
    mxpress/admin_options.php
    mxpress/mxpress_header.php
    mxpress/template_static_home_page.php
    mxpress/template_single_post.php
    mxpress/mxpress_comments.php
    mxpress/functions_template_tags.php
    mxpress/recycle_bin.php
    mxpress/mxpress_index.php
    mxpress/functions_admin.php
    mxpress/functions_admin_selectlogo.php
    mxpress/mxpress.php
    mxpress/functions_content_filtering.php
    mxpress/template_archive_cat_or_terms.php
    mxpress/functions_config.php
    mxpress/readme.txt
    mxpress/functions_navigation.php
    mxpress/style.css
    mxpress/config.php
    mxpress/admin.php
    mxpress/lib/simple_html_dom.php
    mxpress/lib/ga.php

    mxpress_comment()

    and in the code

    function cob_user_role( $user_id ) {
       $user = new WP_User( $user_id );
       echo $user->roles[0];
    }

    where do I Indicate the user role?
    I made a user Role Mods which I want to make a different color and for Admin aswell.

    or should I indicate a specific user? like

    function Cobus_user_role( $user_id ) {
       $user = new WP_User( $user_id );
       echo $user->roles[0];

    or like

    function Mods_user_role( $user_id ) {
       $user = new WP_User( $user_id );
       echo $user->roles[0];
    Moderator bcworkz

    @bcworkz

    You may call the function anything you want as long as there is no other function with the same name. I was actually thinking the declaration could go in your theme functions.php, though in that case it should actually be a child theme. You can put it in a plugin file as well, it doesn’t matter much where as long as it’s loaded when the plugins or themes load.

    There’s nothing to gain by altering the function code itself unless users have more than one role that you need to use. How you call the function could be checked. Passing $comment->user_id is normally the correct reference, but if mxpress changed the $comment object structure in some way, a different reference may be required. Try using var_dump($comment); to confirm.

    I would recommend not using mxpress plugin files for the function code because it will be lost when you update the plugin. It’s bad enough editing the mxpress_comment() function, but there does not appear to be a way to override it. The fewer changes to make after an update the better. You may also make your own site specific plugin to contain miscellaneous hacks and place the function declaration there.

    Were you at least able to identify where to call the function from? It appears to be mxpress_comment(), but that is not certain. Confirm by inserting custom template code and verifying it appears in the comments.

    Some basic debugging might be in order. Implement small parts of the code, verifying each part works before implementing the next. The custom template code is the first step. Next add class="author" to the test HTML entity to check that the role CSS works. Then var_dump($comment) to ensure the user ID reference is correct. Then add in the function call and ensure the source HTML has the role as one of the classes.

    Any failure along the way means you need to take a closer look at code prior to the error but after the last successful trial.

    Once you get this working, I urge you to try to find a clean way to enter an added role class term so you don’t need to reapply the code after each update.

    im really sorry but im a beginner with coding. I understand the issue about updating the plugin will cause the modifications to be lost, but its the only way for it to work since the plugin is being used as the theme aswell.

    Must I input this code
    <div class="existing_ class <?php cob_user_role( $comment->user_id ); ?>">
    into the comments.php witch is indicated underneath and where precisely in the code?

    <?php
    /**
     * The template for displaying Comments.
     *
     * The area of the page that contains both current comments
     * and the comment form. The actual display of comments is
     * handled by a callback.
     *
     */
    ?>
    <br><div id="comments">
        <?php if (post_password_required()) : ?>
            <p class="nopassword"><?php _e('This post is password protected. Enter the password to view any comments.', 'twentyten'); ?></p>
        </div><!-- #comments -->
        <?php
        /* Stop the rest of comments.php from being processed,
         * but don't kill the script entirely -- we still have
         * to fully load the template. */
        return;
    endif;
    
    // You can start editing here -- including this comment!
    
    global $doMxpressComment, $mxpress_options;
    
    if ((have_comments())) :
        if (!$doMxpressComment) {
            ?><br><br><?php
            mxpress_comment_link();
            footer_nav();
            ?><br><br><?php
            //mxpress_debug('have comments, not leaving one');
            $limit_comments = ($mxpress_options['limitCommentsTo']) ? $mxpress_options['limitCommentsTo'] : get_option('comments_per_page');
            $reverse_order = $mxpress_options['orderComments']; //oldest first = 1
            $order = ($reverse_order) ? 'ASC' : 'DESC';
            $post_id = $post->ID;
            $comments = get_comments(array(
                'post_id' => $post_id,
                'status' => 'approve', //Change this to the type of comments to be displayed
                'order' => $order,
                    /* 'number'=>null, */
                    ));
            /* if(!$reverse_order ){
              $comments = array_reverse($comments);
              } */
            /* var_dump($comments); */
            ?>
    
            <br>
    
            <div class="commentlist">
                <?php
                /* Loop through and list the comments. */
                //wp_list_comments('avatar_size=0&style=div&type=comment&callback=mxpress_comment' . $reverse_order . '&per_page=' . $limit_comments . $reverse_order);
    
                wp_list_comments(array(
                    'callback' => 'mxpress_comment',
                    'avatar_size' => 0,
                    'style' => 'div',
                    'type' => 'comment',
                    'per_page' => $limit_comments, //Allow comment pagination
                    'reverse_top_level' => false /* !($mxpress_options['orderComments'])  */  //Show the latest comments at the top of the list*/
                        ), $comments);
                ?>
            </div>
    
            <div class="commentlist">
                <?php
                //Display the list of comments
                ?> </div>
            <?php
            // Are there comments to navigate through?
            //$cpage_count = get_comment_pages_count();
            $cpage_count = ceil(count($comments) / $limit_comments);
            /* var_dump('count($comments)',count($comments));
              var_dump('$cpage_count',$cpage_count);
              var_dump('$limit_comments)',$limit_comments); */
            if ($cpage_count > 1 && $limit_comments) :
                $cpage = get_query_var('cpage');
    
                // figure out nomenclature
                if (!$reverse_order) {
                    //newest first
                    $comments_pagelink_titles = array(
                        'first' => 'Newest',
                        'prev' => 'Newer',
                        'next' => 'Older',
                        'last' => 'Oldest'
                    );
                } else {
                    //oldest first
                    $comments_pagelink_titles = array(
                        'first' => 'Oldest',
                        'prev' => 'Older',
                        'next' => 'Newer',
                        'last' => 'Newest'
                    );
                }
                ?>
                <div class="navigation">
                    <?php
                    $comment_nav_links = array();
                    if ($cpage > 1) { //
                        $comment_nav_links[] = '<a href="' . esc_url(get_comments_pagenum_link(1)) . '"><< ' . $comments_pagelink_titles['first'] . '</a>';
                    } else {
                        $comment_nav_links[] = '<< ' . $comments_pagelink_titles['first'];
                    }
                    $prev = get_previous_comments_link('< ' . $comments_pagelink_titles['prev']);
                    if ($cpage > 1) {
                        $comment_nav_links[] = '<a href="' . esc_url(get_comments_pagenum_link($cpage - 1)) . '"><< ' . $comments_pagelink_titles['prev'] . '</a>';
                    } else {
                        $comment_nav_links[] = '< ' . $comments_pagelink_titles['prev'];
                    }
                    $next = get_next_comments_link(__($comments_pagelink_titles['next'] . ' >'));
                    if ($cpage < $cpage_count) {
                        $comment_nav_links[] = '<a href="' . esc_url(get_comments_pagenum_link($cpage + 1)) . '">' . $comments_pagelink_titles['next'] . ' >></a>';
                    } else {
                        $comment_nav_links[] = $comments_pagelink_titles['next'] . ' >';
                    }
                    ?>
                    <?php
                    if ($cpage < $cpage_count) { //
                        $comment_nav_links[] = '<a href="' . esc_url(get_comments_pagenum_link($cpage_count)) . '">' . $comments_pagelink_titles['last'] . ' >></a>';
                    } else {
                        $comment_nav_links[] = $comments_pagelink_titles['last'] . ' >>';
                    }
                    echo implode(' | ', $comment_nav_links);
                    echo ' (of ' . get_comments_number() . ')';
                    ?>
                </div> <!-- .navigation -->
            <?php endif; // check for comment navigation      ?><br><br>
            <?php
        } else {
            // have comments but leaving one
            mxpress_comment_form();
        }
    else : // or, if we don't have comments:
        if (!comments_open()) :
        // we do nothing
        else:
            if ($doMxpressComment) {
                mxpress_comment_form();
            }
        endif; // end ! comments_open()
    endif; // end have_comments()
    ?>
    </div><!-- #comments -->

    and the cob_user_role must I change it to my username like cobus_user_role or to the type of user role like moderator_user_role?

    Like I said im totaly new into this wordpress code and mxpress plugin doesn’t make it easier since its very different then a normal template, but only the mxpress plugin works via the app im using…

    can you please have a look at the files the mxpress plugin can be found here

    Moderator bcworkz

    @bcworkz

    No worries about being a beginner, we were all there at one time or another 🙂

    Unfortunately, I’m at a loss on how to explain some things. Like the function name. It really can be anything you like, as long as the name is not used anywhere else. There are very few restrictions. It’s a good idea to prefix your initials or something to plain English function names to minimize the chance of a name conflict.

    What ever name you choose, be sure to use the same name when you call the function from where the role/class label is to appear.

    Exactly where you insert the code depends on what parts of the comment you want the color to change. The comment text? Commenter name? Perhaps a border or something? Without knowing that, all I can say for sure is you should insert it somewhere in the 'mxpress_comment() function declaration from your first post.

    The latest code you posted confirms that is indeed the case (the 'callback' => 'mxpress_comment', line), so thanks for that. Now, for example, if you wanted the entire comment text to be colored by role, change this line:
    echo $comment->comment_content;
    to this (assuming you keep my suggested function name):

    $class = cob_user_role( $comment->user_id );
    echo "<div class=\"comment_text $class\">\n";
    echo $comment->comment_content;
    echo "\n</div>\n";

    I know this isn’t much like what I first suggested, but it is actually rather similar. Study the differences and see if you can figure out how they are similar 😉

    If adding the <div> messes up your comment layout, you can correct for it by adding CSS directives to the selector .comment_text.

    Hi ive added that line you specified onto my script and got the following error.

    Fatal error: Call to undefined function cob_user_role() in /home/u506124311/public_html/chatwp/wp-content/plugins/mxpress/functions_comments.php on line 247

    ive added the following codes to my CSS aswell

    .Moderator { color:#ff0000; }
    .comment_text { color:#ff0000; }

    another question is how and where should I specify what the color of the specific user role should be? Or is this correct like I did in the CSS?

    Moderator bcworkz

    @bcworkz

    Where did you put the function declaration? Did you rename the function? There’s two parts to this, the function called in the first part must match the function name in the second.

    $class = cob_user_role( $comment->user_id );

    function cob_user_role( $user_id ) {

    While the names must match, the name can be almost anything. If your code matches like shown regardless of name, then the location of the function declaration (the 4 lines beginning with the ‘function…’ line above) is in the wrong place, it is not getting loaded when it should. The main plugin file or your theme’s functions.php will work. Adding it to the very bottom of either file will usually be correct.

    The .Moderator CSS will dictate the color of the comment text all on it’s own. Be sure the case matches the output in HTML source. Do not specify color in the .comment_text CSS. Use this selector to adjust the spacing of the comment text in relation to adjoining elements. Using margin: and padding: properties is one way to do this. It’s possible you do not need to do anything with .comment_text but it’s available just in case.

    It may not seem like it, but you are close to a working solution. Hang in there!

    I searhed for the line
    echo $comment->comment_content;

    and replaced it with

    $class = cob_user_role( $comment->user_id );
    echo "<div class=\"comment_text $class\">\n";
    echo $comment->comment_content;
    echo "\n</div>\n";

    and added the css mentioned above then it gave me that error

    Can you maybe help me by indicating where Exactly in which document I should place what code or replace witch item. I feel like I’m going in circles since I don’t understand what part to place where. I’m totally confuse. Thank you for your patience with me. I appreciate it.

    Moderator bcworkz

    @bcworkz

    You’re right, we need to take a complete fresh look at the entire set of modifications. There’s nothing actually wrong with the code you inserted that generates the error, the error is due to the function declaration being in the wrong place. I was trying to be efficient and modular by having a function declaration. That turned out to be a bad idea, it just added confusion, let’s try a simpler approach where all the code is in one place. The CSS still needs to be on a different page, but I think you understand that part of it.

    Soooo… Get rid of the function declaration. Replace the same existing line echo $comment->comment_content; with this code:

    $user = new WP_User( $comment->user_id );
    $class = $user->roles[0];
    echo "<div class=\"comment_text $class\">\n";
    echo $comment->comment_content;
    echo "\n</div>\n";

    Then place this code on your CSS page:

    .comment_text {margin: 0 0;}
    .moderator {color: #ff0000;}
    .administrator {color: #000000;}
    .editor {color: #000000;}
    .author {color: #000000;}
    .contributor {color: #000000;}

    This CSS portion will need some editing. All the default roles except subscriber will show up black. Subscribers and not logged in users will be the default color. The comment_text class applies to any user, you can use it to adjust the spacing or anything else about the comment text, such as font, size, line spacing, etc.

    The default roles are all lower case. The roles have both a label and a slug associated with them. The role slug is what is required for CSS selectors. If you’re not sure what the slug is, log on as that role and make a comment, then view the resulting comment HTML source to see what the first code snippet is using. The CSS selector needs to match this.

    Hi Thank you very much Ive implemented it but, there is no change in color …

    There is no errors but the colors just don’t appear. In the case above the.moderator is red but no message we type or send in the comments are read its still black…

    when i type the comment as following into the comment box

    <div style="color:#ff0000">My message</div>

    my message appears in red though but not via the .css to make it default…

    Moderator bcworkz

    @bcworkz

    I’m not sure what you’re trying to tell me, sorry. As for applying an inline style like you did with a div tag in the comment box, that will always override any CSS style sheet, so it’s not very diagnostic. Nice try though 🙂

    You say “In the case above the.moderator is red but no message we type or send in the comments are read its still black…” This sounds to me like you are saying moderator comments appear in red, but I don’t think that is your meaning. I think your meaning is even though the code specifies red for moderator, one’s comments when logged in as moderator are not red, they are still black. Is this correct?

    On what stylesheet did you place the CSS code? Where in the file did you insert it? Closer to the end is usually better. You should also try the !important modifier like so:
    .moderator {color: #ff0000 !important;}

    Getting the desired CSS to be applied to a particular element in WP can be tricky sometimes. There’s often conflicting directives, which ones are applied by the browser follows a specific hierarchy that is difficult to comprehend. There’s many things we can try, but would be very time consuming at the rate we are going. Is there any post with a moderator comment available online that I can see? Preferably with the extra div inserted, but I can work around it being missing.

    If the !important modifier does not work and you inserted the CSS where it is supposed to be, I have some code I know will work, but it’s a rather crude hack which I’d hate to see on anyone’s site. If all else fails, I’ll give you this alternate code just to get you up and running. I would need a list of which roles you want to have displayed in a different color and which color to use for each role.

Viewing 15 replies - 1 through 15 (of 26 total)
  • The topic ‘Mxpress edit to change color of a specific user role name and message’ is closed to new replies.
Skip to toolbar