Half-Elf on Tech

Thoughts From a Professional Lesbian

Tag: plugins

  • WP Comments ReplyTwo

    WP Comments ReplyTwo

    WPTavern has this cool thing where, without threaded comments, you still have a reply link, AND it creates an automatic link back to the original comment.

    Let me rewind. If you have threaded comments, then you get a ‘reply’ link on the bottom of a comment, and it lets you make a threaded reply. Yay! There are problems with this, though, as after a while, if you get nested deep enough, you can’t reply under anymore, and have to go up to click reply on the previous post and on and on.

    Threaded PipeBack eons ago, WPTavern solved this with a function, and like all great sites documented it! The problem? The documentation was busted. Now, yes, I did ping Jeff about this and asked him how it went, but in the meantime, I was impatient and looked up a plugin that almost fit my bill.

    Enter @ Reply (aka Reply To), which add in a reply link to all comments! Plus is gives you ‘Twitter like’ @replies, so when you comment, it starts “@foo:” automatically. This is just like what WPTavern has, perfect! Except… not quite.

    My problems became two:

    1. I want all comments to have a ‘reply’ link.
    2. I don’t want the hover over image.

    And I solved this with two code chunks: a plugin and a theme.

    See, by default WP stops showing you the ‘reply’ link when you can’t nest anymore. To change that, you have to edit how your theme calls comments. Or rather, you have to change the comment_reply_link() call.

    The Theme Code

    I’m already customizing my comments in Genesis so this was surprisingly simple.

    What was this:

    <div class="comment-reply">
        <?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
        </div>
    

    Becomes this:

    <div class="comment-reply">
        <?php comment_reply_link( array_merge( $args, array( 'depth' => 1, 'max_depth' => 2 ) ) ); ?>
    </div>
    

    Basically we’re lying to WP and saying we always show the link. I got that idea from this stackexchange post, and as I understand it, we’re tricking WP by saying that every post is depth of 1, and has a max of 2, instead of letting it figure it out on it’s own. This is probably inelegant, but I couldn’t find another way to have the reply link always on.

    The Plugin Code

    nested-commentsThis was easier, in that I took the existing code, cleaned it up and removed the reply image, and that was pretty much it. Downside is that this does not work on every site. Notably, it doesn’t work unless threaded comments are turned on. When they’re not, it does a double-refresh.

    That said, this is probably never going to be a plugin for the masses, so I’m content with having it work this way for me. Even if I only thread one comment at a time, it would let me group them together and get the @-reply. It’s already rather popular on the site I intended it for, and people like it.

    So here’s the code:

    class AtReplyTwoHELF {
        public function __construct() {
            add_action( 'init', array( &$this, 'init' ) );
        }
    
        public function init() {
    		if (!is_admin()) {
    			 add_action('comment_form', array( $this, 'r2_reply_js'));
    			 add_filter('comment_reply_link', array( $this,'r2_reply'));
    		}
    	}
    
    	public function r2_reply_js() {
    	?>
    		<script type="text/javascript">
    			//<![CDATA[
    			function r2_replyTwo(commentID, author) {
    				var inReplyTo = '@<a href="' + commentID + '">' + author + '<\/a>: ';
    				var myField;
    				if (document.getElementById('comment') && document.getElementById('comment').type == 'textarea') {
    					myField = document.getElementById('comment');
    				} else {
    					return false;
    				}
    				if (document.selection) {
    					myField.focus();
    					sel = document.selection.createRange();
    					sel.text = inReplyTo;
    					myField.focus();
    				}
    				else if (myField.selectionStart || myField.selectionStart == '0') {
    					var startPos = myField.selectionStart;
    					var endPos = myField.selectionEnd;
    					var cursorPos = endPos;
    					myField.value = myField.value.substring(0, startPos) + inReplyTo + myField.value.substring(endPos, myField.value.length);
    					cursorPos += inReplyTo.length;
    					myField.focus();
    					myField.selectionStart = cursorPos;
    					myField.selectionEnd = cursorPos;
    				}
    				else {
    					myField.value += inReplyTo;
    					myField.focus();
    				}
    			}
    			//]]>
    		</script>
    	<?php
    	}
    
    	public function r2_reply($reply_link) {
    		 $comment_ID = '#comment-' . get_comment_ID();
    		 $comment_author = esc_html(get_comment_author());
    		 $r2_reply_link = 'onclick=\'return r2_replyTwo("' . $comment_ID . '", "' . $comment_author . '"),';
    		 return str_replace("onclick='return", "$r2_reply_link", $reply_link);
    	}
    }
    
    new AtReplyTwoHELF();
    

    Most of the javascript stuff is copy/pasta for me (just left of witchcraft), and I left it barebones (no configurations) on purpose. Simple is as simple does.

    Suggestions and tweaks welcome!

  • Adding Per Site Multisite Options

    Adding Per Site Multisite Options

    johnc- said in IRC the other day, regarding the use of get_option API for WordPress “our standard practice is to use get_option to enable site specific features, if the feature needs to be unavailable for other sites then it gets broken into a separate plugin for clarity”

    diceSo to explain this for those who blinked a little we need some examples, and really this depends what you’re writing.

    We got to this point in the conversation while folks were watching my “Don’t Use WordPress Multisite” presentation from WordCamp SF. During the presentation, I mentioned that generally, when I want to write a function for a specific site on Multisite, I wrap it around a ‘If site 1, then …’ and put it in it’s own plugin file in mu-plugins. That leaves me with files like halfelf-functions.php so if I ever split the site out (see? I’m always thinking ahead) I know what file to copy.

    But that’s not the only way about it. Another way is to put all the functions in a file, and then wrap the actual filters and actions around a get_option call. Why would I want to do this instead of a separate function file? The question of portability comes up primarily. Exporting site options is not the easiest thing in the world on a Multisite, but there are cases, like my Capital H Dangit! function, where this would make sense. In general, I always want DreamHost to have a capital H, so since 99% of my sites have that on, I could, instead, use an option, since if I ever moved the one site that doesn’t use it, I just won’t bring the function over!

    Currently have wrapped that function around an ‘if site 2, then don’t run’ check, which works fine. But if I wanted to move that to options, it would go like this:

    
    // Add the default option of capital h to yes, and autoload
    add_option( 'helf_capital_H_dangit', 'yes', '', 'yes');
    
    if ( get_option( 'helf_capital_H_dangit' ) == 'yes' ) {
        foreach ( array( 'the_content', 'the_title', 'comment_text' ) as $filter )
            add_filter( $filter, 'capital_H_dangit', 11 );
    }
    
    function capital_H_dangit( $text ) { 
        [... code here ...]
    }
    

    This is pretty basic. It adds an option called helf_capital_H_dangit, auto-loads, and defaults to on for everyone. That was the easy part. The hard part is determining how to control it.

    One option is an interface where I can check a box on, say, General Settings > Writing > Formatting (right under the smilies check box would be perfect), but since I knew this was something I was going to want to control as the super-admin (that is, I don’t want the other people on my network to turn it off), I went in to the back end of my site at /wp-admin/network/site-info.php?id=2 (since this is site ) and searched for ‘Helf’

    Screen Shot 2013-08-21 at 2.21.41 PM

    I edited it to ‘no’ and saved. Boom. I can use DreamHost and Dreamhost here.

    Now this isn’t something I’d do for everything. In fact, my actual halfelf-functions.php file looks like this:

    global $blog_id;
    
    if ( $blog_id == 2 ) {
    
    	remove_filter( 'the_content', 'capital_P_dangit', 11 );
    	remove_filter( 'the_content', 'capital_H_dangit', 11 );
    
    	// I Make Plugins Filters
    }
    

    All the per-site filters are right there turned off as I want them. It’s not a lot of effort that way, and it’s still easy to pick up a site and drop it somewhere else.

    Businesswoman in Front of DoorsWhich is better? I don’t know. The real test would be to do some hardcore speed checks and see if checking for the blog ID is faster than checking for an option. I think the speed benefit gains would come from only calling this when needed, but for the limited world in which this is used, it should be fine. Also, keep in mind what both johnc- and I are saying, but in different ways: remember the 80/20 rule.

    In my opinion, if you’re making a feature that will be used by 80%+ of the sites on your Network, get_option is probably the easiest bet. If you’re making a feature that’s going to be used by 20%- of the sites, then a separate plugin (with a site_id check) is the way to go. Of course, you could do an option and default it to ‘no’ as well, but that brings up an interesting level of things to remember if you ever move a site.

    If you’ve got a more efficient way of doing the same thing, or even just a different way, speak up! More options are always better.

    Oh and no, we’re not going to sneakily install this on DreamPress, but if I did, it would also capitalize DreamPress, DreamCompute, and everything else out there. But I won’t.

  • MP6uccess – Tips and Tricks

    MP6uccess – Tips and Tricks

    Notice: Since WordPress 3.8 came out, you DO NOT need to install MP6 for anything to work. Promise. If you want the extra color schemes, use Admin Color Schemes, but everything else works in core WP.

    nyan-catI like MP6. It’s far, far, far easier for me to read the back end of WordPress with it. It has legible fonts, larger fonts, and best of all, it’s mobile friendly.

    The biggest complaint has been that it’s too dark. And I get that, I really do. I personally have trouble seeing white on black (computers only), and white on green (yes, road signs). So for me, the black sidebar was a little heavy, but something I could live with. Then version 2.0 came out and behold, color schemes!

    I immediately ran this update, zipped to my profile page (where I knew it had to be), and saw this:

    mp6-scheme

    The other options right now are Blue (looks like the old blue), Seaweed, Pixel, and Ectoplasm. Seaweed is my favorite, but I decided to make each site a little different and distinct, so I have Ectoplasm running right now on one site and Seaweed on the other. I can tell right away which is which. My only wish is the toolbar was colorized on both ends.

    Tips & Tricks

    Okay, okay, I’ll stop selling the plugin, and instead tell you what’s cool to do with it.

    Styling Menu Items

    The items on your menu sidebar default to some pretty boring icons. Bleah. For years we’ve always uploaded our own images to change things in our plugin and custom post types. Here’s an example for my own code for an old Custom Post Type, because I wanted a custom video icon to show up on my sidebar:

    function cptname_post_type_css() {
       echo "<style type='text/css' media='screen'>
               #menu-posts-CPTNAME .wp-menu-image {
                    background: url(/path/to/CPTNAME.png) no-repeat 6px -17px !important;
            }
               #menu-posts-CPTNAME:hover .wp-menu-image, #menu-posts-CPTNAME.wp-has-current-submenu .wp-menu-image {
                     background-position: 6px 7px!important;
            }
        </style>"
    }
    add_action( 'admin_head', 'cptname_post_type_css' );
    

    Now that I’m using MP6, I have access to Dashicons, which already has a video icon included, so I can use this:

    function cptname_post_type_css() {
       echo "<style type='text/css' media='screen'>
               .mp6 #adminmenu #menu-posts-CPTNAME .wp-menu-image:before {
                    content: '\\f126';
                }
             </style>";
    }
    add_action('admin_head', 'cptname_post_type_css');
    

    Menu with VideoNo need for a hover image, because this is a font and not an image, so the hover is automagically taken care of. The result is exactly what I wanted. It looked just like it was built into WordPress from day one, and my co-authors know right where they’re supposed to go to make a new video post.

    There are a lot of options to nab from, and there’s a double edged sword to having some ‘standards’ built in. While it’s super easy for me to make a plugin or CPT use what I want, the same goes for other people. I imagine a lot of shopping cart plugins will want to use '\f174' (the shopping cart) if they don’t have their own. Also it means that to ‘match’ you’ll have to use Font Icons yourself, and they’re not super easy to make. Not that everyone worries about matching.

    Force a Choice

    Okay, what if you want to force a choice for everyone?

    add_filter('get_user_option_admin_color', 'change_admin_color');
    function change_admin_color($result) {
        return 'ectoplasm';
    }
    

    This is the same as it’s always been, actually. But now everyone gets to use purple and green, yay! Keep in mind, this is a hard force. Everyone uses this. There’s no changing. I have this on one site, since the ecotplasm color actually matched the theme. I set it, went away for the weekend, and found the users laughing and loving the perfect match.

    Also check out…

    I’m sure I’m not the first person do dig out these tricks for MP6. At WordCamp Chicago I remarked that a cool plugin would be “MP6SS” – it would let you pick four colors (similar to the blocks the current MP6 plugin offers), and you could make your own colors on the fly. A little dangerous, but the next option up from that would be a fork of the CSS plugin in Jetpack, which lets you totally customize your MP6 CSS 100%.

    Here’s some links I’ve found to more MP6 fun:

    Do you have any tricks? Post links to your code!

  • DreamCon In Review

    DreamCon In Review

    atimThe weekend after WCSF I talked at DreamCon, which was our own little Webhost convention/camp for technology and other things. As Matt said, we’re kind of the wacky Webhost, and I love it that way here at DreamHost.

    Some of my coworkers talked about the technical stuff, like WP-cli and how DreamPress works, but I talked about some slightly more esoteric and conceptual things, no coding involved topics, because I tried to think about the questions people who host with us asked me the most.

    Choosing WordPress Plugins

    This was the more geeky of the two, but was an overview on how I search for plugins, value the devs and their work, and determine which ones I use. I mentioned needs and wants a couple times, which makes me think I’ll end up giving people a talk on that one of these days…

    The questions I got after this session were interesting. I preemptively answered the long standing question I had never been able to answer before, which is “What is your favorite plugin?” I finally have an answer, and it’s MP6. My eyes suck, and for me, MP6 finally made the back end of WordPress totally readable for me, without having to increase my browser’s font size. The font was better, and larger, and clearer. Normally I hate black backgrounds, but for some reason MP6 doesn’t give me headaches.

    The best question I got was how to search effectively. My answer was to be more exact with search terms. Too often we go for broad terms and narrow down, but I like to go the other way. “wordpress plugin calendar event list” – I pick every major term I need in that plugin, and more precise results follow.

    Get Out Of The Monkey House

    Besides the fact that all the devs in the room cheered when I stated “code is art” I think this one really opened people’s eyes. Remembering that the design of your site doesn’t stop at the pretty stuff, that your content and the flow of how the site works is also a major impact, is huge.

    By the way, code is totally art. You’re making something out of nothing, inventing and building a concept that never existed before. It’s just like writing music. Be proud of it. The most standout question from this talk was what do I do when a customer demands they stay in that monkey house? I put my foot down. When I get into contract work, I have always stated up front “You’re hiring me to be your expert, which means you may suggest things for your website that I, out of my experience and expertise, know to be bad ideas. When that happens, I will tell you that we should not do these things, and why. This is my power of veto. I will only use it when I have proof, via research, that what you are proposing is not in your best interests. If that’s not okay, then we don’t sign the contract. If it is, then you will accept my actions on web design, just as I will accept yours about your product. You know more than I do about that, I know more than you about this.”

    tumblr_ma1mh5Cpbs1rdkmnho1_500

    Thus far, no ones walked away, and I’ve never made a website with a blink tag (except for the gag website, where the contract was to make it look like Ling’s cars…).

  • To Fork Or Not To Fork

    To Fork Or Not To Fork

    ForkinRoad Sometimes the question you have to ask yourself is if you should fork. With a plugin, this is a fairly easy conversation. You want functionality, the original author doesn’t, you fork. But when you look at a theme, you start getting into messier territory.

    In many ways, a theme is ‘simpler’ than a plugin. Theme devs, don’t shoot me! What I mean is that a plugin can be or do anything, but a theme is always a theme. While it may change how your site looks in amazing ways (and I am constantly in envy of people who can visualize like that), it really is just a theme. This is why reviewing themes is easier to monitor and manage than plugins. But that’s another conversation. The point here is that when you want to extend a theme, you make a child theme. Done.

    What happens when you’re already using a child theme, though? StudioPress, a theme shop I love, makes child themes and sells those. This site is using a child theme, though it’s currently one of my own devising. Previously, it was using a child theme called Streamline, however, and it had a lot of changes.

    So when do you make a child theme, and when do you extend it in other ways? It really depends on what you’re doing. While I sat and tried to figure out where my personal breakpoints were, I realized that since the best themes know they are a theme, and not a plugin, it was really easy. A great theme lets you seamlessly use a plugin to add in functionality. They may even tell you what the best ones are. Recently, Coen Jacobs wrote about how good themes never bundle plugins and he’s right. A plugin is a plugin, a theme is a theme. Keep ’em separate, keep ’em safe.

    I’ve done it in three different ways for three different sites, and I’ll explain my rational below.

    The Simple

    Fork+in+the+roadOne site is simple. Every ounce of functionality I needed, and more, was in the core code of StudioPress, not even a child theme was needed. All I wanted was to change some colors and add in a couple CPTs and shortcodes. That was easily done via Jetpack, which has a CSS editor, and a couple plugins. Actually, 99% was the CSS, once I sat down and looked at it. All the weird stuff was normal plugins.

    Sometimes simple is a teeny bit complicated, and when that happens, I may make a custom mu-plugin or two, but in general, not so much needed unless I want a Custom Post Type. And anyway, I never put a CPT in my theme if I can help it.

    The Complicated

    On the other hand, one site is hella complex. I found a theme I really, really, liked. Almost. And worse, this was a child theme. It was exactly what I was afraid of. There was no way I would get what I wanted out of this theme unless I edited the functions.php file, a lot of the CSS, and a ton of the images. Could I still have done this via CSS and a couple plugins? No. Well, the CSS yes, but not the code. I had need for some crazy functions, a total re-write of comments, and the list went on.

    In this case, I forked. I ripped out the small amount I never wanted. I added in the medium amount I did want. I directly edited the theme’s CSS, added in a post template, and changed all the images to my chose color. I even added in a different font. Could I have re-written from scratch? Of course, but the theme had 90% of what I already wanted to do.

    There actually is a step before forking, and that would be using plugins. I know I mentioned plugins before, with the simple themes, but actually most theme frameworks are extra special. They often have custom plugins like Simple Hooks, which fundamentally lets me do everything I might do in a functions.php file for that theme. This means most of the time, I don’t fork. But. This theme really was so complex that I needed more than just the simple hooks. Genesis Complex Hooks may have done it, or another plugin to make a transient functions.php (ala CSS editing). And that would have done it except for when I wanted to change a lot of images, add in JS, and then a custom page template …

    Well you see how it goes. The point here, however, is that I sat and thought about it, studied my setup, and made a long term decision. Originally I was using the plugin way, but when it stopped being extendable, I decided to do this, and I regret nothing.

    Fork_In_The_Road

    The Original

    The last option I had was I theme I kind of liked, but it was old. It was pre-HTML5, it didn’t have microformats, but more-over, it wasn’t aging as well as I would have liked. I made a list of what I liked about it, what I didn’t, and what I really wanted. While the list was short, it was also clearly not going to just be CSS. I wanted a custom front page, an extra page template, images, and Genericons built in. In short, I wanted this theme to be something that could carry me onward, regardless of a plugin, even one I wrote.

    I have not made my own, 100% from scratch, child-theme in a long while, and this one may not really count since I was designing it to look like something else. This took me an afternoon to bang out the basics, and a couple days of minor fixes here and there to perfect them. Release and iterate, as they say. Certainly, I could have taken someone else’s theme, but it was going to be a surprising amount of work to do that. Instead, I made a list of my needed features and my desired options, and went to town. It’s still a pretty simple child-theme (which speaks well to the inherent extensibility of the parent), but now it’s mine, and it’s easy to extend it and expand it.

    The Rest…

    What about you? What do you think about when deciding how to handle a theme that needs changing?

  • Not RSS 2 Email

    Not RSS 2 Email

    37679586Back in 2011, I made an RSS powered email list using rss2email. The last new version was released that year, and while the last two years have worked perfectly well, there’s one small problem. The developer appears to be done with it. This happens, and the beauty of open source is that people can pick up the code, fork it, and carry on. The annoyance is that sometimes the new coders do things that break it all for you. In this case, the running fork of rss2email uses Python 3.2 or higher.

    If you’re using Python 3.2+, grab rss2email the new version and off you go! But if, like me, you’re on a server that doesn’t come with that version of Python, you can start swearing. This is not something you can just upgrade, either as Daniel Eriksson explains how to do this on CentOS 6 (my flavor). Many different flavors of Linux use the old 2.x branch of Python, and there are no plans I’ve seen to upgrade any time soon.

    Now I’m faced with a dilema. Do I mess around and upgrade on my own, or do I find another answer. You know I went with option B, right?

    I sat and thought really hard about what I, personally, needed this to do. This is a key component to any code you’re going to write. Make sure you know what you need. Let’s break things down:

    Needs

    • Email to be sent to a specific address automatically when there’s a new post.
    • No email sent on pages or CPTs
    • Post ‘excerpt’ is message content

    Wants

    • Change ‘to’ email on the fly.
    • Select full post or post excerpt in email
    • Customize ‘from’ email address

    Dream Future

    • Ability to say “no, not this post”
    • Customize email message
    • Allow options for different post types to get emailed

    That’s pretty simple, isn’t it? It’s clear cut what I need, what I want, and what I’d like to have if I have time. Not every project is this simple, but today it is.

    I actually knew how to do my ‘needs’ already, but as soon as I tested it I found I had to expand on what I meant by ‘when there’s a new post.’ If I hooked into the publish_post action, the email got sent every time a post was updated too. This lead me down to Notifly, which emails a list of people for every post and comment, but not post updates. That gave me the magic of transition_post_status, which solved that first problem.

    At this point, the question became “Why not just use Notifly?” The first problem I had was that it sent out emails for comments too, with no easy way to turn that off. I could have forked, and I started looking into that when I ran into problem two, which was I couldn’t change the ‘from’ email. This was something that became a bigger issue later, when I realized I needed to be able to change the from email to work better with restrictions on certain hosts and with certain mailing lists. I could still edit the plugin, but I looked at what that plugin did and what I needed and wanted. Editing Notifly to do what I wanted would mean overcomplicating it and adding a lot more options. I could fork it, but I’d be stripping everything out and rewriting if I did that, so I decided to carry forward with my own thing. I would say the plugins are similar, cousins, but approach the goal in different ways. Semantics, I know.

    Once I mastered only emailing on post publish, I had to tell it not to email on non-posts. No emails being sent on CPTs and pages was easy and I could have used is_post_type() and checked for posts, but I decided to use get_page(), because that let me expand on some other features later. This was new to me, but since I wanted to use the post excerpt, this was going to be, bar none, the fastest way to pull that in.

    While I love being able to read whole posts in my RSS reader, I lose a lot with it, in regards to formatting. For the site I desired to run this on, the layout is a huge thing. On top of that, thanks to some idiots, I had to turn on hotlink protection, lest they crash my server again. Also I use a lot of embedded media (HTML5 video, twitter, etc). That means the ‘whole’ post generally looks like crap. So for every single post, I custom craft an excerpt. And this is why get_page() was awesome, because I could use that to pull the excerpt.

    EmailsThe default WordPress emails are sent from ‘wordpress@yourdomain.com’ with the name ‘WordPress’ and while that’s great, I wanted mine to be sent from ‘Blogname’ (the email address was fine, I’ll just add it to the email list as a moderator). That changed my ‘want’ of being able to customize the from info into a ‘need’ but it was also pretty easy to do.

    If I was only going to use this code on one site forever and ever, I’d probably leave it at this. But … I know I’ll want to use this around other places. I started by looking at my ‘wants’ and put those in as well.

    So what did I end up with?

    Post2Email

    This is a simple WordPress plugin that lets you set a to email, a from email, and a from ‘name’. It uses the RSS settings to determine if your email body is the full text or the excerpt. It only emails on posts, not pages or CPTs, and not for private posts. You can only set one email because of reasons, first being I only need to send to one address, but second is that I really hate when people send me emails I don’t want or need. Limiting the number of emails you can send to will help that. It also helps you not piss off your webhost by spamming people. Seriously. You use my plugin to spam people, I will hurt you.

    What about my dream features? Handling the different post types means using get_post_types(), which isn’t horrible. In theory it’s just a check ‘If the option for that post type isn’t checked, fail out.’ It’s not something I need, and I really don’t feel like auto-emails for everything is a good idea (pages and CPTs are not posts!), so I’m going to wait and see if this is a need for people.

    Flagging per post I have no idea how to do, since I don’t yet know how to put a custom post option like that per-post and check it on publish. Yet. Since public posts are public, I think that it’s fine having it email on all public posts. Opting out like that is not for me, but if enough folks come up with it, I’ll consider it because it’s a good excuse to learn something new.

    Customizing the message is easy and when I went back in to fiddle with internationalization and proper content serialization, I added it in. I also went and used wp_parse_args to remove setting the defaults in the database, and make it easier for me to add more options in later.