Link Card for Another Post Shortcode
Adds a [post_card] shortcode that shows another post or page as a card with its image, title and excerpt, perfect for "see also" links inside articles.
Opens WPIDE on
Code
add_action( 'init', function () {
wp_register_style( 'wpide-post-card', false, array(), '1.0' );
wp_add_inline_style( 'wpide-post-card', '.wpide-post-card{display:flex;gap:1rem;align-items:center;margin:1.5em 0;padding:.75rem;border:1px solid rgba(0,0,0,.15);border-radius:8px;text-decoration:none;color:inherit}.wpide-post-card:hover,.wpide-post-card:focus{border-color:currentColor}.wpide-post-card img{width:120px;height:80px;object-fit:cover;border-radius:4px;flex:none}.wpide-post-card strong{display:block;margin-bottom:.25em}.wpide-post-card span{font-size:.9em;opacity:.85}@media (max-width:480px){.wpide-post-card img{width:80px;height:60px}}' );
add_shortcode( 'post_card', function ( $atts ) {
$atts = shortcode_atts( array( 'id' => 0, 'slug' => '', 'type' => 'post' ), $atts, 'post_card' );
$post = $atts['id'] ? get_post( absint( $atts['id'] ) ) : get_page_by_path( sanitize_title( $atts['slug'] ), OBJECT, sanitize_key( $atts['type'] ) );
if ( ! $post || 'publish' !== $post->post_status || post_password_required( $post ) || get_the_ID() === $post->ID ) {
return '';
}
wp_enqueue_style( 'wpide-post-card' );
return sprintf(
'<a class="wpide-post-card" href="%s">%s<span><strong>%s</strong><span>%s</span></span></a>',
esc_url( get_permalink( $post ) ),
has_post_thumbnail( $post ) ? get_the_post_thumbnail( $post, 'thumbnail', array( 'alt' => '', 'loading' => 'lazy' ) ) : '',
esc_html( get_the_title( $post ) ),
esc_html( wp_trim_words( get_the_excerpt( $post ), 20 ) )
);
} );
} );
Notes
Example [post_card id="42"] or [post_card slug="pricing" type="page"]; only published items are shown.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.