1
\$\begingroup\$

For WordPress sites, I always end up building custom post types. They usually have categories, but I don't use much of the 'archive' abilities. This site, for example, is for a film director and so it has "project" resources and then have the standard 'category' taxonomy. I find myself copying and pasting this code in blocks to list each category.

It seems like there are 2 ways to go with PHP. You can keep the markup clear and work the PHP into it, or stay mostly in PHP land and echo markup. I think PHP is a fine language - but simply the syntax has lead me to JS frameworks in its place:

{{#each things as |thing|}}
  <li>{{thing.name}}</li>
{{/each}}

Regarding custom fields, I am far more accustomed to ACF vs CMB2, but recently worked on a project with CMB2 and I kinda saw some light in creating the template with more PHP... but both ways still seem less than awesome.

Here's the block of code I find myself using the most. I do it so much that I have a version with xxxxx where project is - that I use to just find and replace with the resource name.

The markup isn't always exactly the same - so I paste it rather than build a function that just takes 1 parameter of resource - but I could have conditionals

What say you - brave code reviewers? How can I up my game with this? Simplify? Change my view-point? Just relax? build a function? Best practices?

Should I be using some archive template for repeating post-type categories instead?

<section class='container projects one'>
<div class='inner-w'>

  <?php
  // =========================================
  // Define the rules/arguments
  $project_args = array(
    'post_type' => 'project',
    'showposts' => '-1',
    'category_name' => 'documentary',
  );

  // The Query
  $project_query = new WP_Query($project_args);

  // The Loop
  if ( $project_query->have_posts() ) { ?>

    <h2 class='category-title'>Documentary</h2>

    <ul class='project-list'>

    <?php
      while ( $project_query->have_posts() ) {
        $project_query->the_post();

        $image = get_field('project_poster');
    ?>

          <li class='project'>
            <a class='link' href='<?php the_permalink(); ?>'>
              <figure class='poster'>
                <?php
                  if ( $image ) {
                    $poster = $image['sizes']['medium'];
                  } else {
                    $poster = 'https://placehold.it/1600x900';
                  }
                ?>
                <img src='<?php echo $poster; ?>' alt='<?php echo get_the_title(); ?> poster image' />
              </figure>
              <h1 class='title'><?php the_field("project_title"); ?></h1>
            </a>
          </li>

        <?php } ?>

    </ul>

  <?php } else { ?>

    <?php // what happens if there are no posts? ?>

  <? } ?>

  <?php wp_reset_postdata(); /* restore original post data */ ?>

</div>
</section>


<?php // repeat many blocks like the 'section' above ?>
\$\endgroup\$
2
  • \$\begingroup\$ To be clear, are you wanting to list custom post content by it's taxonomy terms (in this case the taxonomy is 'category') ? If that is the case and you do this on a custom post archive page, then you already the correct custom post type available to you. \$\endgroup\$
    – davemac
    Commented Jun 16, 2017 at 1:48
  • \$\begingroup\$ Good point @davemac - but it's not always my case. Sometimes I want to have 3 of each or something on the front page as teasers to the archives etc. I'll remember to employ that though! \$\endgroup\$ Commented Jun 16, 2017 at 15:47

1 Answer 1

2
\$\begingroup\$

First off, Wordpress is an awful platform when it comes to separation of business logic from display logic. If you expect to continue working in it, you can expect to continue to feel the pain that you are feeling.

The thing that concerns me the most about your comments, is that you say you cut/paste this code repeatedly. That immediately screamw out for putting this code into a widget or function so that it is reusable. Think if you had a function like:

display_category_list($post_type, $category_name, $show_posts = -1)
{
    // your code
}

This would simplify your main pages to have calls like:

display_category_list('project', 'documentary');
display_category_list('foo', 'bar');

So that could solve the copy/paste problem.


Now let's get into the problem of display templating. Even working with basic PHP output mechanisms, you can greatly clean up your code, simply by separating out the logic from the HTML in a more reasonable fashion. You could structure your code like this:

display_category_list($post_type, $category_name, $show_posts = -1)
{
    // Define main section template.
    // You could just as easily include this to keep template
    // in a separate file
    $section_template = <<<'EOT'

<section class='container projects one'>
<div class='inner-w'>
{{list}}
</div>
</section>
EOT;

    // list template, again could be included
    $list_template = <<<'EOT'

    <h2 class='category-title'>{{category_name}}</h2>
    <ul class='project-list'>
    {{items}}
    </ul>
    </h2>
EOT;

    // item template
    $item_template = <<<'EOT'

        <li class='project'>
            <a class='link' href='{{link}}'>
                <figure class='poster'>
                    <img src='{{poster}}' alt='{{poster_alt_text}} poster image' />
                </figure>
                <h1 class='title'>{{title}}</h1>
            </a>
        </li>
EOT;

    // Actual function logic
    $args = array(
        'post_type' => $post_type,
        'showposts' => $show_posts,
        'category_name' => $category_name,
    );
    $query = new WP_Query($args);

    // put default "no post" content here (this could come from template as well)
    $list_content = '';
    if($query->have_posts()) {
        $list_content = str_replace('{{category_name}}', $category_name, $list_template);   
        $items = '';
        while ($project_query->have_posts()) {
            $post->the_post();
            $link = the_permalink();
            $poster = (get_field('project_poster')) ?
                $image['sizes']['medium'] : 'https://placehold.it/1600x900';
            $poster_alt_text = get_the_title();
            $title = the_field('project_title');
            $template_data = array(
                '{{link}}' => $link,
                '{{poster}}' => $poster,
                '{{poster_alt_text}}' => $poster_alt_text,
                '{{title}}' => $title
            );
            $items .= str_replace(
                array_keys($template_data),
                array_values($template_data),
                $item_template
            );
            $items .= PHP_EOL;    
        }
        $list_content = str_replace('{{items}}', $items, $list_content);
    }        
    echo str_replace('{{list}}', $list_content, $section_template);            
    wp_reset_postdata();
}

Note how I have moved the HTML into templates defined within nowdoc blocks. This approach can allow you to easily pull this content out of the function itself into separate template files that are easier to manage. For example, the function could be rewritten with template-to-variable assignments like this:

$section_template = include('/path/to/section_template.php');

With the template file looking like:

return <<<'EOT'

<section class='container projects one'>
<div class='inner-w'>
{{list}}
</div>
</section>
EOT;

This means you could even go so far as to pass template file paths into the function on the fly to switch out templates to be used (or you could have some config settings for template paths that the function uses). This could totally get you out of having any HTML within the function itself.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks for your time @Mike Brant. I guess some things are just ugly. I'm glad to know I'm not crazy! \$\endgroup\$ Commented Jul 23, 2017 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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