Search code examples
phpwordpressdatedivi

Add class to post articles on Divi post module


I have been attempting to add a class to the list of posts on a Divi page 'Blog' module (i.e. a list of posts). I have searched extensively for a solution but have not found one online as yet.

I want to just use the year each post was published. So for each post listed, I want to add the class as follows:

<article id="1" class="prefix-[year]">....</article>
<article id="2" class="prefix-[year]">....</article>
<article id="3" class="prefix-[year]">....</article>

I have attempted to work out how to do this as an addition to the functions.php file in my child theme based on a slug class function I already use, but unsuccessfully (I'm a novice on this front).

My attempt below throws an error on the site (which is unsurprising!).

function add_year_class($classes) {
    global $post;
    foreach((get_post_datetime($post->post_date)) as $date)
        $classes[] = date("Y", strtotime($date);
    return $classes;
    }
add_filter('post_class', 'add_year_class');

Any suggestions on how to achieve this appreciated.

Just to re-iterate, this is the Divi Blog module rather than the stock Wordpress blog/archive page if that makes a difference to the code/functionality.


Solution

  • Divi probably doesn't provide hook for this thing.

    The easiest solution would be getting the year from the post published date (element with class "published" inside each "article") on the front-end:

    jQuery(($) => {
      $("div.et_pb_posts article").each((i, el) => {
        const regex = /(\d{4})/; //Let's assume you use "M j, Y" date format (can be set in Divi Blog module)
        const articleDate = $(el).find("span.published").text().trim();
        const [articleYear] = articleDate.match(regex) || [];
        $(el).addClass("year-" + articleYear);
      });
    });
    

    If you want to have class name which consist only of the custom class:

    jQuery(($) => {
      $("div.et_pb_posts article").each((i, el) => {
        ...
        $(el).removeClass().addClass("year-" + articleYear);
      });
    });
    

    If you want to remove the date element (so it would be used only for class creation):

    jQuery(($) => {
      $("div.et_pb_posts article").each((i, el) => {
        ...
        $(el).find("span.published").get(0).previousSibling.remove();
        $(el).find("span.published").remove();
      });
    });
    

    Combined:

    jQuery(($) => {
      $("div.et_pb_posts article").each((i, el) => {
        const regex = /(\d{4})/;
        const articleDate = $(el).find("span.published").text().trim();
        const [articleYear] = articleDate.match(regex) || [];
        $(el).removeClass().addClass("year-" + articleYear);
        $(el).find("span.published").get(0).previousSibling.remove();
        $(el).find("span.published").remove();
      });
    });