foreach loop in wordpress working just once when creating shortcode

i want to create a shortcode [twf-link-to-post category="6" numberposts="3" order="DESC"]for wordpress by which i can call recent post. below code is what i have try in functions.php

function post_link_shortcode($atts)
    {
    // Attributes
    extract(shortcode_atts(array(
        'category' => '',
        'numberposts' => '',
        'order' => ''
    ) , $atts));
    // Code
    if (isset($category))
        {
        $recent_posts = wp_get_recent_posts($atts);
        foreach($recent_posts as $recent)
            {
            $twf_recent_post = '<a href="' . get_permalink($recent['ID']) . '">' . $recent['post_title'] . '</a><br />';
            return $twf_recent_post;
            }
        }
    }
add_shortcode('twf-link-to-post', 'post_link_shortcode');`

loop in this code bring just one post and i want it to fetch post whatever gives in shortcode.

Related posts

Leave a Reply

1 comment

  1. you need to concat the string check the code below 🙂

    function post_link_shortcode($atts)
        {
     $twf_recent_post='';
        // Attributes
        extract(shortcode_atts(array(
            'category' => '',
            'numberposts' => '',
            'order' => ''
        ) , $atts));
        // Code
        if (isset($category))
            {
            $recent_posts = wp_get_recent_posts($atts);
            foreach($recent_posts as $recent)
                {
                $twf_recent_post .= '<a href="' . get_permalink($recent['ID']) . '">' . $recent['post_title'] . '</a><br />';
    
                }
    return $twf_recent_post;
            }
        }
    add_shortcode('twf-link-to-post', 'post_link_shortcode');