The Divi theme comes with a blog module, which lets you display a list of posts anywhere on your site, complete with featured image, excerpt and read more button. If you'd like to add a second button beside posts in the Divi blog module, here's a way to do it.
I've had a bit of a play around and come up with a basic implementation (in PHP). In this example I'm adding a "Buy Tickets" button with a URL taken from a custom field.
First, here's the code:
add_filter('et_pb_blog_shortcode_output', 'dbc_add_second_buttons_to_blog_module', 10);
function dbc_add_second_buttons_to_blog_module($content) {
return preg_replace_callback('/<article.*?<\/article>/s', 'dbc_add_second_button_to_article', $content);
}
function dbc_add_second_button_to_article($match) {
if (isset($match[0])) {
$html = $match[0];
$article = false;
preg_match('/<article id="post-(\d*)"/', $html, $article);
if (isset($article[1])) {
$id = intval($article[1]);
if ($id) {
$url = get_post_meta($id, 'buy_tickets_url', true); // Fetch url from post's custom field
if (!empty($url)) {
$button = '<a href="'.esc_attr($url).'" class="more-link">Buy Tickets</a>';
$html = preg_replace('/(<a[^>]+class="more-link">)/s', $button.'\\1', $html);
}
}
}
}
return $html;
}
Related Post: Adding PHP to the Divi Theme
It looks a bit complicated, but don't let that put you off – what it's doing is reasonably straightforward. it modifies the HTML generated by the by the blog module, and then finds each article element in that HTML (corresponding to each blog post shown by the module).
For each article, it grabs the post id from the article's id attribute. It then tries to retrieve the ticket URL from a custom field called 'buy_tickets_url' from the post (I'll explain this in a bit). If it finds a ticket URL, it adds a "Buy Tickets" link with that URL alongside (actually, before) the read more link. Then the updated HTML gets returned to be displayed by the blog module.



A couple of notes:
- The extra button will be added to any blog module in which the post appears.
- The code adds the "more-link" class to the new button, so that it will adopt the same styles as the standard "read more" link.
0 Comments