How to create a custom WordPress shortcode for displaying random testimonials

James T Dec 18, 2024 Shortcodes
How do I make a special code to show random reviews on my site?
What steps do I need to follow to create a custom WordPress shortcode that outputs random testimonials from a custom post type?
Andy answered Dec 18, 2024

Creating a Custom Shortcode for Random Testimonials

Basic Approach

Let's create a solution that will:

  1. Register a custom post type for testimonials
  2. Create a shortcode to display random testimonials
  3. Add basic styling options
  4. Handle error cases

Step 1: Register Testimonials Custom Post Type

First, let's create the testimonials post type in your theme's functions.php:

function register_testimonial_post_type() {
    $args = array(
        'public' => true,
        'label'  => 'Testimonials',
        'supports' => array('title', 'editor', 'thumbnail'),
        'menu_icon' => 'dashicons-format-quote'
    );
    register_post_type('testimonial', $args);
}
add_action('init', 'register_testimonial_post_type');

Step 2: Create the Shortcode Function

Here's the main shortcode function that displays random testimonials:

function random_testimonial_shortcode($atts) {
    // Parse attributes
    $atts = shortcode_atts(array(
        'count' => 1,
        'class' => 'testimonial-box'
    ), $atts);
    
    // Sanitize inputs
    $count = absint($atts['count']);
    $class = sanitize_html_class($atts['class']);
    
    // Query testimonials
    $args = array(
        'post_type' => 'testimonial',
        'posts_per_page' => $count,
        'orderby' => 'rand',
        'post_status' => 'publish'
    );
    
    $testimonials = new WP_Query($args);
    
    // Start output buffering
    ob_start();
    
    if ($testimonials->have_posts()) {
        while ($testimonials->have_posts()) {
            $testimonials->the_post();
            ?>
            <div class="<?php echo esc_attr($class); ?>">
                <div class="testimonial-content">
                    <?php the_content(); ?>
                </div>
                <cite class="testimonial-author">
                    <?php echo esc_html(get_the_title()); ?>
                </cite>
            </div>
            <?php
        }
    } else {
        echo '<p>No testimonials found.</p>';
    }
    
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('random_testimonial', 'random_testimonial_shortcode');

Step 3: Add Basic Styling

Add this CSS to your theme's style.css:

.testimonial-box {
    padding: 20px;
    margin: 20px 0;
    background: #f9f9f9;
    border-left: 4px solid #ddd;
}

.testimonial-content {
    margin-bottom: 10px;
    font-style: italic;
}

.testimonial-author {
    display: block;
    font-weight: bold;
    color: #666;
}

Usage

Use the shortcode in your posts or pages:

  • Basic usage: [random_testimonial]
  • Multiple testimonials: [random_testimonial count="3"]
  • Custom class: [random_testimonial class="my-custom-class"]

Security Considerations

  • Always sanitize inputs (implemented in the code)
  • Use WordPress escaping functions (esc_attr, esc_html)
  • Verify nonces if adding admin features
  • Limit query results to published posts only

Common Pitfalls to Avoid

  1. Don't forget to reset post data after custom queries
  2. Avoid direct database queries when WordPress functions exist
  3. Don't hardcode HTML without escape functions
  4. Consider performance with large numbers of testimonials

Plugin Alternatives

If you prefer a ready-made solution:

  1. Strong Testimonials

  2. Easy Testimonials

    • Simple implementation with multiple display options
    • Plugin Page

Enhancement Options

  1. Add custom fields for:
    • Rating
    • Company name
    • Profile picture
  2. Implement AJAX loading
  3. Add category filtering
  4. Create transition effects

Performance Tips

  1. Use transients for caching results
  2. Limit the number of testimonials queried
  3. Optimize images if using featured images
  4. Consider lazy loading for multiple testimonials

This solution provides a solid foundation that you can customize based on your specific needs while maintaining WordPress best practices.