Tag: Web Development

  • WordPress challenge of the day: sorting by meta value, including posts WITHOUT that meta value set

    I dug around quite a bit for a solution to this today, and eventually I found one, even though it’s a bit ugly.

    The problem here is in setting up a WordPress query that sorts posts based on a meta value. I wanted to sort a list of pages by template, but I wanted to include all of the pages, even ones that don’t explicitly have a template set. But the default query was only showing the ones that did have the template value.

    Several dead ends almost led me to give up, until I realized it was a JOIN issue. Specifically, the need to change an INNER JOIN to a LEFT JOIN. I just needed to figure out how to do that in the context of WP_Query.

    Cut to the chase, here’s what I ended up with.

    add_action('pre_get_posts', function($query) {
      if (!is_admin()) { return; }
      $orderby = $query->get('orderby');
      if ('_wp_page_template' == $orderby) {
        $query->set('meta_key','_wp_page_template');
        $query->set('orderby','meta_value');
        // Workaround to include items without this meta key
        // Based on: https://core.trac.wordpress.org/ticket/19653#comment:11
        add_filter('get_meta_sql', function($clauses) {
          $clauses['join'] = str_replace('INNER JOIN','LEFT JOIN',$clauses['join']) . $clauses['where'];
          $clauses['where'] = '';
          return $clauses;
        });
      }
    });

    I don’t like doing a str_replace() on part of the pre-built query, but sometimes you gotta do what you gotta do. Also note that this is part of a larger function I am writing that is only for use in the admin side; you could remove that is_admin() check if you want this to work everywhere.

    I haven’t had a chance to dig into the details of the query to figure out why the original source post included moving $clauses['where'] into $clauses['join'], but it’s essential. I tried skipping it, and it didn’t work.

    Sorry I can’t provide any more context here… but I hope it’s helpful to anyone who finds themselves in a similar situation!

  • Some problems just never go away… especially where CSS3 multi-columns are concerned

    Note: This post has been updated.

    I don’t use CSS3 multi-columns (based around the column-count and column-gap properties) very much, mainly because a) I don’t need columns in my layouts very often and b) usually when I do need columns, this method is inadequately flexible for what I’m trying to accomplish.

    Today I have a good use case though. A simple (but long) list of links, that I want to display as 3 columns on wide screens, 2 columns on tablets and a single column on phones. Great, except when I got it working, I found that — in Chrome only, which is a bit odd — the top of the first column is higher than the rest. It looks fine in Safari and Firefox.

    I googled, as always, for a solution, and found several suggestions that seemed like they should work, and people claimed they did work, but for me, they didn’t. Then I found this comment on a post on the topic, and decided to try the column-break-inside property, which is something I normally only use in print CSS.

    It still didn’t work. But then, vendor prefix to the rescue! I needed the -webkit prefix, and it worked. This needs to be applied to the elements inside your column container, not the container itself. Here’s my full CSS block:

    .columns {
      -moz-column-count: 3;
      -webkit-column-count: 3;
      column-count: 3;
      -moz-column-gap: 3em;
      -webkit-column-gap: 3em;
      column-gap: 3em;
    }

    /* Fix for unbalanced top alignment in Chrome */
    .columns > * {
      -webkit-column-break-inside: avoid;
      column-break-inside: avoid;
    }

    You’ll also want to repeat the .columns section (or its equivalent for your class/element names) in your media queries, changing column-count appropriately where you want to collapse down to fewer columns.

    Since other solutions worked for other people, I’m guessing my solution might not work for everyone either. But I hope it helps someone… maybe you!

    Update (6/28/2017)

    This problem really does never go away. And I’ve just run into a situation where the above fix doesn’t work. This is only affecting Safari — I think Chrome has actually fixed the bug. But some trial and error led to this new solution that fixes the problem in Safari as well.

    /* New fix for Safari */
    .columns > * {
      display: inline-block;
      width: 100%;
    }

    I’m still not totally sure why display: inline-block; is the magic bullet for column alignment issues, but it works. Adding width: 100%; is what keeps these inline blocks from actually appearing on the same line, if they’re short enough. (Also note that I removed the column-break-inside stuff… don’t seem to need it with this change.)

    Update (6/12/2020)

    Wow… it really never goes away, does it?

    Now I’ve found that if I am applying my .columns class to a <ul> tag, its <li> tags lose their bullets, because they apparently need to have display: list-item (or have it implied). When did display: list-item get added to the CSS spec anyway? I’d swear it didn’t even exist when I was first working on this issue, but I’m an old fart now and time has lost all meaning.

    Anyway… I did manage to figure out a workaround to this. So add the following after the update above (which you’ll still keep):

    /* New fix for Safari */
    .columns > li {
      display: list-item;
      margin: 0 !important; /* Maybe you won’t need !important */
      padding-bottom: 0.5em; /* Add some padding to make up for any margin you’re losing above */
    }

  • How to REALLY check if the content is empty in WordPress

    Problem: You want to check if the content in a WordPress post is empty. Seems easy, but do a Google search on the topic and you’ll see the question asked and — incorrectly — answered several times.

    The fact is, I know how to do this. I was just hoping there was a built-in function in WordPress that I didn’t know about. Apparently not, so I wrote my own.

    Why isn’t it easy and obvious how to check for the content being empty? Well, you could do this:

    if ($post->post_content == '') { ... }

    That will work. If the content is really empty. That means a zero-length string. As in strlen($post->post_content) == 0. Which it might be. But probably not.

    If you’ve worked with real world site content, or even someone else’s Word documents before, you know that blank space is invisible, and a lot of times there’s a lot of blank space in a document that is not truly “empty.” Spaces, line breaks, HTML paragraphs with nothing but a non-breaking space in them. It all takes up space, and makes the content look empty, even when it’s not.

    That last example is the critical one here. A WordPress post may look like it has no content, but if someone pressed Enter while the cursor was in the content box and then saved the page, it most likely has at least one <p>&nbsp;</p> in it.

    So what you need is a function that takes all of that invisible cruft into account. Since it doesn’t seem like WordPress has such a function built in, I wrote my own, which I have made as compact as possible:

    function empty_content($str) {
        return trim(str_replace('&nbsp;','',strip_tags($str))) == '';
    }

    This function takes the string you pass into it, strips out all HTML tags, then removes any non-breaking space entities, and then trims all whitespace. If there’s nothing but that stuff, then it becomes an empty string. If there’s any “real” content, the string won’t be empty. Then it just compares whatever it has left against an actual empty string, and returns the boolean result.

    So now if you want to check if the WordPress content is really empty, you can do this:

    if (empty_content($post->post_content)) { ... }

    This will return true if the content is empty; false if it’s not.

    Update (8/31/2017): This post continues to be one of the most frequently viewed on my blog, and I’ve been meaning for ages to amend it with this important note. As written here, you’ll get an erroneous true returned if the only content is in HTML, for instance, an image. If you want the function to return false if there’s no text content, then leave it as-is. But you can add a second input parameter to the strip_tags() function to tell it to leave certain HTML tags alone. If you want to allow image tags, for instance, the modified code would read as such:

    function empty_content($str) {
        return trim(str_replace('&nbsp;','',strip_tags($str,'<img>'))) == '';
    }

  • How to really exclude the home page in the WordPress wp_page_menu() function

    I’m posting this little tip for my future self as much as for anyone else.

    The problem: It seems that in recent years WordPress has all-but-deprecated the wp_page_menu() function in favor of the wp_nav_menu() function, but the latter is primarily intended for Custom Menus, and there are some cases where Custom Menus aren’t what you want.

    I’m working on a couple of sites right now that have a lot of pages, and I don’t want their editors to have to go over to Appearance > Menus every time they add or move a page. I’m relying on the CMS Tree Page View plugin on these sites to allow the clients to leverage the built in Parent / Order settings on pages to manage their primary navigation, rather than managing a separate Custom Menu.

    Since I’m not using a Custom Menu, I don’t want to use wp_nav_menu() at all; I pretty much have to use wp_page_menu(). Which is fine. Except for the fact that the site designs do not call for having Home in the navigation.

    No problem, right? After all, I can just add 'show_home' => false to the arguments passed to the function, and it will remove the home page.

    But it doesn’t.

    I’m not entirely sure what’s going on in the WordPress core here, but I suspect that show_home only works if you’re using the old school default configuration of WordPress that calls for the home page being the main “posts” page. And who does that anymore? If you’ve created a custom home page, even if you’ve configured WordPress properly to display it as the main page, this function doesn’t care. (Do functions “care” about anything? But I digress…)

    Remember also that there’s an exclude argument, to which you can pass a comma-delimited string of post IDs to exclude. That works, but… ugh. You mean I really have to hardcode the post ID of the home page right into my header.php file?

    Of course not. Use this: get_option('page_on_front') and it will automatically find the home page. This is great if you want to be able to reuse a theme or custom function on multiple sites or just not commit the transgression of hardcoding something that really doesn’t need to be hardcoded.

    Here’s the complete code sample. Note there’s no need to bother with show_home at all.

    wp_page_menu(array(
        'exclude' => get_option('page_on_front'),
    ));

  • The (highly biased) case against CSS preprocessors

    Everybody who’s anybody is using CSS preprocessors!

    Or so it feels. I’m an old-school vanilla CSS curmudgeon, and the more I’ve dipped my toes into working with CSS preprocessors (specifically, SCSS with Compass), the less I like them.

    As I see it, there are three main problems with vanilla CSS:

    No variables. Honestly this is probably the only problem I really have with CSS. I’d like to be able to set variables for things like colors that I use throughout a site. To a lesser extent, I see the benefit of “mixins” — reusable chunks of CSS.

    Redundant code. It really depends on how you conceptualize your CSS structures, but it is very easy to fall into a habit of writing the same CSS code over and over again, resulting in bloated, hard to maintain files. While I am guilty of this just like anyone else, I find that if you format your CSS code properly you can combine properties efficiently to avoid redundancy without needing any external solutions.

    Lack of programmatic logic. Here I’m thinking about things like conditional statements, and also math operations. This is probably as much of a strength as a weakness. CSS is a stylesheet, not a program. It’s a set of rules to be applied to formatting a document. There’s nothing programmatic about it. But still, as CSS selectors become more complicated and convoluted, it is clear that in some cases light programming logic would be helpful.

    The real question is, do CSS preprocessors actually solve these problems? Or, more specifically, do they solve them without introducing new problems that are at least as bad as the ones they’re trying to fix?

    For me the answer has been, and continues to be, no, they don’t. But I’m trying to get a more tangible explanation for why that is, rather than the simple gut feeling that’s been driving me away from using them up to this point.

    What are other people saying?

    My first stop in trying to answer this question of why I dislike CSS preprocessors was Google. I wanted to see what other people were saying, pro and con. Here are some interesting blog posts I found, going back a few years to the early (or at least earlier) days of CSS preprocessors:

    The problem with CSS pre-processors
    This article by Miller Medeiros was the first one I came across a few months ago when I initially pondered this question, and at the time it was all I needed to satisfy myself that I was not crazy for wanting to avoid CSS preprocessors.

    So, assuming preprocessors do solve the problems with vanilla CSS, what are the problems they introduce? And how bad are they, really?

    I need to get specific to my own situation for a minute here. I have a former coworker who is a firm believer in SCSS, and now that he’s gone, I’m left to maintain and extend the code he was writing. This experience casts my aversion to CSS preprocessors into stark relief.

    Maintenance can be a challenge

    The most obvious issue with using a preprocessor is that the output CSS is not exactly easy to hand edit, and worse, you shouldn’t hand edit it, because your changes don’t end up back in the original SCSS (or whatever format you’re using) files. If someone else goes back in later and edits the original SCSS and generates new CSS, your changes will get lost.

    But let’s set that matter aside for a minute. In a broader sense, one of the key challenges for any web developer is to build code that is easy to maintain. Not just for you to maintain, but for whoever comes after you to maintain. Face it, you’re not going to be working on this project forever. At some point, someone else is either going to need to take it over, or throw away what you did and start fresh.

    If you’ve ever jumped into an existing project midstream, or been handed the task of maintaining something someone else built — especially if it’s something built by someone who is no longer around to answer your questions — you know that it’s rarely an ideal situation. Even if the previous developer left copious documentation, it can take hours of picking apart their code to really get a firm understanding of how it all works. This is true with plain CSS too, but at least with plain CSS it’s a lot less work to track down a particular piece of troublesome code.

    It’s non-standard

    What happens when certain features of your favorite preprocessor get rolled into a future version of vanilla CSS? What happens if similar (but incompatible) features of a different preprocessor become the standard? In short, what if everything you’re doing right now becomes obsolete? How long are you going to hang on to doing things your old way with your no-longer-relevant preprocessor, before you have to scrap it and start over, or at least rewrite big chunks of your code to fit the new way everyone is doing things?

    Call me a curmudgeon, but having been a professional web developer for over 18 years I’ve seen a lot of technologies and design trends come and go. I’ve always been skeptical of anything non-standard. I never used VBScript or ActiveX, I never embraced Flash, and in general I’ve done everything I could to both champion and adhere to open standards as much as possible throughout my career.

    Suffice to say, resisting CSS preprocessors is just in my blood. They just don’t feel right to me. I’d rather do without features I want, if they’re not part of the standard, than resort to a non-standard workaround to make them happen… especially if it looks like there’s a reasonable chance they’ll be added to the standard at some point in the not-too-distant future.