How to Implement a Custom Card Output for LPS

Here is a small snippet that allows you to use the Latest Post Shortcode plugin framework while also getting wild and creative with the results.

How to Implement a Custom Card for LPS

Introduction

The Latest Post Shortcode WordPress plugin allows you to create a custom static or dynamic selection of posts (of any type) and output that in many places on your website, either by using a classic shortcode or a Gutenberg block.

The plugin is equipped with filters for changing the card elements’ patterns (check out the older snippet and some details about that), and starting with 11.4.0, the plugin offers also the option to build and hook up your completely custom output, using two simple filters.

You can download the free plugin from the WordPress repository.

PHP Snippet

The snippet used two filters: one for registering a custom output type that becomes available for the editor to select in the UI, and the second one that changes the output for the cards rendered with the shortcode you configure to use the custom output type.

<?php
/**
 * Hooks for Latest Post Shortcode 11.4.0
 *
 * @package textdomain
 */

declare( strict_types = 1 );

namespace IuliaCazanSnippets\LPS;

\add_filter( 'lps/card_output_types', __NAMESPACE__ . '\\lps_card_output_types', 1 );
\add_filter( 'lps/override_card', __NAMESPACE__ . '\\lps_override_card_output', 10, 5 );

/**
 * Change the list of card output types.
 *
 * @param  array $types Initial list of output types.
 * @return array
 */
function lps_card_output_types( array $types = [] ): array {
	// This is an example.
	$types['as-custom-card'] = __( 'Custom card', 'textdomain' );
	return $types;
}

/**
 * The custom output of the card.
 *
 * @param  string   $markup  The computed markup for the current card.
 * @param  string   $pattern The card pattern used for the initial markup.
 * @param  \WP_Post $object  The post object used for the card output.
 * @param  array    $args    The shortcode arguments.
 * @param  string   $type    The card output type.
 * @return string
 */
function lps_override_card_output( string $markup, string $pattern, \WP_Post $object, array $args, string $type = '' ): string {
	// Check for the custom output type and do the changes only for that one.
	if ( 'as-custom-card' === $type ) {
		// Apply the changes you want or replace the markup completely.
		// $markup = '...';
	}

	return $markup;
}

If you would like to support my work, consider making a donation, buy me a coffee, or share this on your feed.
A huge thanks in advance!

Iulia Cazan
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.