WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Automatically adding text to comment after comment is submitted (61 posts)

  1. Mark / t31os
    Moderator
    Posted 5 years ago #

    To add, in case you get stuck figuring out how to add it to each comment in a theme that uses wp_list_comments...

    You'll need to create a custom callback for the comments..

    Then do the jiggery pokery in the theme functions.php...

    What this guy wrote seems quite helpful... and i think he's onto something regarding the regex...

    http://www.russellbeattie.com/blog/mobile-browser-detection-in-php

  2. asechrest
    Member
    Posted 5 years ago #

    Ok, had a little bit of time to hash out a basic structure. Here's what I have so far (with most of the credit to t31os). I used the strategy in that link you gave, t31os.

    Currently this simply tests to see if a comment is made from a Mozilla agent, and if not it appends "Not...Mozilla..." to the end of the comment.

    I've still got to finish the coding and make it more efficient, but what do you guys think so far? Tips and criticisms welcomed.

    add_filter( 'comment_text', 'mobilesig' ); 
    
    function mobilesig ($mytext) {
    
    //GLOBALS
    global $comment;
    
    //VARIABLES
    $mytext;
    $is_mobile = false;
    $str_comment_agent = strtolower($comment->comment_agent);
    
    		// !== OPERATOR TAKES PRECENDENCE. See http://www.php.net/manual/en/language.operators.comparison.php
    		//EVALUATES TO TRUE OR FALSE (1 OR 0) AND ASSIGNS TO $is_mobile
    		$is_mobile = strpos($str_comment_agent, 'moz') !== false;
    
    		if (!$is_mobile) {
    			$mytext = get_comment_text( $comment ) . '<p style="border-top: 1px solid #0C14F0; margin: 30px 0 0 0; padding: 2px 0 0 0;"><small>Not Posted From a Mozilla Agent!</small>';
    			return $mytext;
    		}
    		else {
    			return $mytext = get_comment_text($comment);
    		}
    }
  3. Mark / t31os
    Moderator
    Posted 5 years ago #

    It's short and simple... :)

    You can do this directly in the theme functions if you use a comments callback, i'll give an example...

    In theme comments.php
    <?php wp_list_comments('type=comment&amp;callback=mytheme_comment'); ?>
    Functions file

    <?php
    function mytheme_comment($comment, $args, $depth) {
       $GLOBALS['comment'] = $comment; ?>
       <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
         <div id="comment-<?php comment_ID(); ?>">
          <div class="comment-author vcard">
             <?php echo get_avatar($comment,$size='48',$default='<path_to_url>' ); ?>
    
             <?php printf(__('<cite class="fn">%s</cite> <span class="says">says:</span>'), get_comment_author_link()) ?>
          </div>
          <?php if ($comment->comment_approved == '0') : ?>
             <em><?php _e('Your comment is awaiting moderation.') ?></em>
             <br />
          <?php endif; ?>
    
          <div class="comment-meta commentmetadata"><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"><?php printf(__('%1$s at %2$s'), get_comment_date(),  get_comment_time()) ?></a><?php edit_comment_link(__('(Edit)'),'  ','') ?></div>
    
          <?php comment_text() ?>
    
          // Do your stuff here...
    
          <div class="reply">
             <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
          </div>
         </div>
    <?php
            }
    ?>

    Of course this restricts the code to the theme, rather then working at a plugin level...

    I'm not sure it matters hugely though... but that's how i did when i was testing the comment_agent... it seemed easiest...

    Though in theory you're not running each comment through an additional filter, and i'd expect overall load times to be faster in this case...

    Could do with the OP offering some input at this point i think... :)

  4. asechrest
    Member
    Posted 5 years ago #

    My theme has the comment callback, so I guess I got lucky when testing. I'm not clear on why the callback is required for the filter to work on wp_list_comments() though. (I guess the other way to list comments would be a regular comments loop?)

  5. asechrest
    Member
    Posted 5 years ago #

    Maybe I'll throw this all in a plugin with a short options screen just for practice. Never written one before.

  6. Mark / t31os
    Moderator
    Posted 5 years ago #

    You need the callback because otherwise there is no way to add anything into the comments loop without running the comments through a filter...

    wp_list_comments() is that loop so to speak...

    You don't need the filter if you plonk your code it in the comment loop/callback...

    My point simply being, this can be done at a theme level without any additional filters.

  7. asechrest
    Member
    Posted 5 years ago #

    Ahhh, I see. I never even considered not putting it in the theme's functions.php file. I forgot I could have also just stuck the code in the comment loop.

    That's what I get for jumping into WordPress coding at the filter level. Now I can't do anything but write filters. ;-)

    By the way thanks for the help on this, it's been a pretty good learning experience. I'll have to finish the code up this weekend to make it a working filter.

  8. Mark / t31os
    Moderator
    Posted 5 years ago #

    Well as soon as i knew the comments table had a field for the user agent the first thing i did was ask myself how comments are looped...

    The theme i use has wp_list_comments, so i hit the codex and created a custom callback, it was then a matter of guessing/assuming how to call that field...

    In this case..
    $comment->comment_agent

    I assumed $comment was an object which is the result from the comments table, so then i reference the necessary field, that being "comment_agent"..

    Testing locally means i can run any code without fear of opening a gaping security hole...

    So while testing i do alot of...

    <?php
    print '<pre>';
    print_r($somevar);
    print '</pre>';
    ?>

    and..

    <?php
    print '<pre>';
    var_dump($somevar);
    print '</pre>';
    ?>

    Also turn on full error reporting and notices...

    I also have this little function for printing out handy info..

    function variable_array_dump($var_name, $var_array) {
    	if (is_array($var_array)) {
    		$output = "
    	<table width='100%'>
    		<tr>
    			<td width='20%'><b>" . $var_name . "</b></td>
    			<td><b>VALUE</b></td>
    		</tr>
    		";
    		foreach ($var_array as $key => $value) {
    			$value = variable_array_dump($key, $value);
    			$output .= "
    		<tr>
    			<td>$key</td>
    			<td>$value</td>
    		</tr>
    		";
    		}
          $output .= "
    	</table>
    	";
    	return $output;
    	}
    	else {
    		return strval($var_array);
    	}
    }
    //echo variable_array_dump('SOMENAME', $_SERVER);

    The commented bit is an example, in this case i get a print out of what's been stored in $_SERVER, but you can use, $_POST, $_GET, or just about anything else... (It's not 100% perfect, but it works for most things - grabbed it off google)...

    It definately helps to know what variables and requests are being made on each page load, especially if you're working on a plugin or function... though for most things a var_dump or print_r is sufficient..

  9. asechrest
    Member
    Posted 5 years ago #

    Nice. I'm totally snagging that function. Right now I've just been testing on my live site. Horrible idea, I know, but I haven't set anything up locally yet.

    If I'm able to make this into a little practice plugin I'll give it to you guys for testing/tearing apart. :)

  10. asechrest
    Member
    Posted 5 years ago #

    I'll have a small plugin ready later tonight. Mostly used as coding and plugin writing practice, but perhaps it's useful as well.

    Either of you willing to help me test it? I have no mobile phone to post from. The best I've been able to do is fake a mobile comment using a variable, but it's not exactly real-world testing.

    And t31os, if you have time I wouldn't mind you just taking a look at it anyway. Then you can warn me of the dire security risk I've opened up on all of the plugin's users. ;-)

  11. Mark / t31os
    Moderator
    Posted 5 years ago #

    Be happy to test it... i'm still learning the plugin stuff myself, curious to see how you approach it...

    I'm sure there's an easy way to spoof the user agent for the sake of testing, just have to spend a few mins on google...

    Zip it up and post a link when you're ready..... :)

    Can always revise, so don't worry about having everything perfect.. :)

  12. asechrest
    Member
    Posted 5 years ago #

    Warning to anyone not following the thread. The following links to a plugin that's only lightly tested. Use at your own risk for now.

    Ok t31os, here's the link to download the zip.

    Any/all criticism, tips, etc. welcomed. The most interested part so far has actually been creating the options page. Still planning a checkbox to turn on/off the comment text, only have the variable to control it so for, haven't coded it to the options page.

    Have various other ideas bouncing around my head but let me know what ya' think.

  13. asechrest
    Member
    Posted 5 years ago #

    P.S. - I'm actually working backward here. My coding experience is basically a year and a half of CS courses a bunch of years ago (none in PHP), so I'm pretty much just diving in and learning/refreshing my memory as I go.

    Consequently I'm actually hoping for tips and enlightenment. So don't hesitate to tear the code apart and recommend stuff.

  14. Mark / t31os
    Moderator
    Posted 5 years ago #

    Looks decent enough mate.

    Few minor HTML errors, here and there (block level elements inside inline elements), but apart from that it looks suited...

    I'd fiddling with a few bits and have added a few minor bits for you, i'll plonk it up in a pastebin when i've finished fiddling... since it's only a single file...

    I plonked it in a folder when installing it, i'm not a fan of plugins sitting in the root of the plugin folder, prefer that they each have their own folder, but that's a personal preference..

    Will post back later once i've got some other things done... :) Nice work...

  15. asechrest
    Member
    Posted 5 years ago #

    Nice, interested to see what ya' added. Play with it all you want and I'll pick through your code and comments to see how it works. :)

  16. Mark / t31os
    Moderator
    Posted 5 years ago #

    Ok, here we go...

    http://wordpress.pastebin.com/m4e8ff87f

    Removed a few un-necessary bits, and added a few extra bits..

    Importantly though, your section for..add_options_page

    Should have been set to more than 1, since this sets the user_level able to access the page... i typically go for 8....

    We could proberly do away with your additional bits relating to user_level but i left them and focussed on other bits..

    You could add some session and token bits in, but it's really not necessary for something so basic...

    Ideally the variable that's passed along to update_option() should have some sanitization done before being sent along (because you're placing user input into the database with this function), but again for something this simple it may be a little overcautious....

    Primarily i've updated the preview area to look more like an actual comment (ok not perfect, but a little more comment-like)... and updated the html and css... the rest was me just playing around ... :)

    Do with it as you will.... it's your code now.. ;) ...

  17. asechrest
    Member
    Posted 5 years ago #

    Nice, will take a look in a couple hours. Took a glance and it's going to be fun seeing what you did. Already have a question or two so I may post back again. ;-)

    Good point on the user_level. Woops.

    Re: Session and token bits. Explain a little? I'm in the dark on this one.

    Re: Sanitization - Like running it through wp_filter_kses? Was just reading an old thread on that today. My question is how much sanitization does update_options do?

  18. Mark / t31os
    Moderator
    Posted 5 years ago #

    Sessions and tokens just help make sure the submissions are valid by storing some information inside the session and form (tokens), these will only match once, so this makes it alot harder for cross-site-scripts to exploit etc..

    Sanitizing data is important though, again this just ensures no naughty code is plonked into the form...

    You can do that any number of ways, but you have to decide what can and can't be put in the field before you go invalidating submissions..

    preg_match, strip_tags...etc.. it all depends what level of filtering you want...

    Yes like filter_kses ... (i've not used that one, though did actually find a page on that the other day)...

    I'll send you the plugin i've been playing with if you want something to toy with, if you like... (it's a bit of a mess, but it's been a learning experience, and the jquery was quite fun to)...

    I'm still learning to... ;)

  19. asechrest
    Member
    Posted 5 years ago #

    Yep please send. I just like to read through the code and tinker around with stuff. :)

  20. Mark / t31os
    Moderator
    Posted 5 years ago #

    Ok, going to be cryptic with the link here, and i'm only going to keep it active a little while...

    I don't want this link found by bot spiders and the like, so please don't post the decoded link... it'll be down soon anyway...

    Take the following...

    aHR0cDovL3d3dy50MzFvcy5jby51ay93cC1jb250ZW50L3VwbG9hZHMvc25pcHBldHMucmFy

    Use PHP and run base64_decode on that string....

    You'll then have your link.. :)

  21. asechrest
    Member
    Posted 5 years ago #

    Got it, you can shut it off. Thanks.

  22. Mark / t31os
    Moderator
    Posted 5 years ago #

    Okies :) ...

    Be as critical as you like with it.... i'm dying for some feedback, since it's a constantly ongoing project....

    Was intending to release the plugin for others soon, but i've not had time to work out the final bits and pieces just yet... (spending too much time here)... :)

  23. asechrest
    Member
    Posted 5 years ago #

    Want me to post to your site once I have a chance to look at it? Or keep it in this thread?

  24. Mark / t31os
    Moderator
    Posted 5 years ago #

    I don't mind mate, whichever you prefer... :) here is good..

  25. asechrest
    Member
    Posted 5 years ago #

    Finally getting a chance to pick this back up. Hey t31os (or anyone else reading)...

    So we can grab the user agent a comment was made from with $comment->comment_agent.

    BUT, I don't see anything similar for a post. Am I missing it?

  26. t31os
    Member
    Posted 5 years ago #

    What exactly are you after? I'm still reading.. :)

  27. asechrest
    Member
    Posted 5 years ago #

    Well, something like post_agent. Except that doesn't seem to exist. On the comment side of things, WordPress stores the user agent that was used when the comment was published (obviously, since you and I have been working with this).

    Buuuuuut, I can't find anything similar for a post. Obviously we can grab the user agent of a user, but I just figured if we had a comment_agent we'd have a post_agent or something similar.

    Otherwise I'm stuck needing to write a function(s) that detects an author's user_agent at the time of post publish and stores that information in connection with the post, right?

    P.S. - Started looking at your plugin code. It's really a pretty interesting concept, though some of it is way over my head yet. Still picking through it, though. :)

  28. Mark / t31os
    Moderator
    Posted 5 years ago #

    No there doesn't appear to be anything in the post's table that stores the user agent..

    I'd at least recommend if you're going to hook a function to post publish that you use a seperate DB table. Otherwise you'd have to modify the posts table, and i'd say avoid doing this where possible, just to keep things simple if the person using the plugin wants to remove it, they've not got to drop additional columns or work with a modified post table.

    RE: the plugin
    It's admittedly not all my work, it's a mod of the connections plugin, but i've changed quite a bit... it's been fun playing with it...

    Any suggestions? General comments? ... bugs?

  29. asechrest
    Member
    Posted 5 years ago #

    Haven't actually installed it yet, just opened it in my code editor and spent some time looking at the functions. I hadn't even looked at our plugins in over a week. Been too busy.

    But I'll be trying it out this weekend.

  30. asechrest
    Member
    Posted 5 years ago #

    For those that come across this thread and are looking for this functionality, I developed a small plugin to append user-defined text to comments made from a mobile phone.

    The plugin is called Mobile Comments Signature, and can also be downloaded at the Mobile Comments Signature plugin page on my website.

Topic Closed

This topic has been closed to new replies.

About this Topic