This code snippet will generate a shortcode [custom:mp-random-posts] that you can add to your newsletter in MailPoet to show a list of (five in this case) posts older than one year. Every subscriber will receive a unique list of articles.

Of course, you can modify the date_query or posts_per_page values in the $args variable. Feel free to modify the name of the shortcode in the code below, having in mind that MailPoet requires it to follow the naming structure: [custom:xxxxxxxx].

To use the code, add it to the functions.php file in your theme or via a plugin like Code Snippets or my favourite WPCodeBox (affiliate link.)

Finally, add the generated shortcode to your newsletter’s text box in MailPoet and use the Preview button to see if everything works as intended.

add_filter('mailpoet_newsletter_shortcode', 'mailpoet_custom_shortcode', 10, 6);

function mailpoet_custom_shortcode($shortcode, $newsletter, $subscriber, $queue, $newsletter_body, $arguments) {
    if ($shortcode !== '[custom:mp-random-posts]') return $shortcode;
  
    $args = array(
        'post_type' => 'post',
        'orderby'   => 'rand',
        'posts_per_page' => 5,
        'date_query' => array(
            array(
                'column' => 'post_date_gmt',
                'before' => '1 year ago',
            ),
        ),
    );
 
    $the_query = new WP_Query( $args );
 
    if ( $the_query->have_posts() ) {
    $string .= '<ul>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
        }
        $string .= '</ul>';
        wp_reset_postdata();
    } else {
        $string .= 'no posts found';
    }

    return $string; 
}

Leave a Reply

Your email address will not be published. Required fields are marked *