0

My website has been up for 10 years and as such has gone through various layout changes. Whenever I have made a new layout, I have added all news stories that were made under that layout into a new Wordpress category so I could target said stories and keep the same layout applied to them. This is the code I've used:

<?php rewind_posts(); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php if ( in_category('2563') ): ?> (layout coding)
<?php elseif ( in_category('919') ): ?>  (layout coding)
<?php elseif ( in_category('3') ): ?> (layout coding)
<?php else: ?> (layout coding)
<?php endif; ?>
<?php endwhile; ?>

I'm once again changing my layout, but I don't want to keep making new categories since it just makes things look messy. So I was wondering if there was a way to instead of basing the news story layouts on category, to base them on their creation date. So I would like to be able to do something like... "if X story was published between 7/15/03 at 1:03 PM and 9/19/07 at 11:34 AM, use the following layout." Like the code above, but with time/date ranges. Does anyone know if this is possible? Thank you so much!

1

Conceptually, that isn't hard to do.

if (have_posts()) {
  while (have_posts()) { 
    the_post();

    if ( $post->post_date >= date("Y-m-d H:i:s",strtotime('7/15/03 1:03 PM'))
         && $post->post_date <= date("Y-m-d H:i:s",strtotime('9/19/07 11:34 AM'))) ) {
      // (layout coding)
    } elseif ( /* another condition */ ) { 
      // (layout coding)
    } elseif ( /* another condition */ ) {
      // (layout coding)
    } else {
      // (layout coding)
    }

  }
}

You can skip the strtotime if you just use MySQL format dates-- YYYY-MM-DD HH:MM:SS (24 hour time)-- to start with.

That will become pretty cumbersome over time. It may already be quite a long ifelse sequence, especially with the layout markup interspersed like that. Unfortunately, unless there is a pattern to your format changes that may be unavoidable. You can make that more manageable by using get_template_part.

} elseif ( /* another condition */ ) {
  get_template_part('layouts/','layout2');
}

Your layout markup would be in wp-content/themename/layouts/layout2.php. That should make things more readable and maintainable.

Also, you don't need all those opening and closing PHP tags. You only need those when you switch from PHP to HTML. They are not markers for line starts and stops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.