Search code examples
phpwordpressfunctionshortcode

Return multiple results with same short code


I added a function in functions.php and it works fine for one result with a link mentioned in $link however I am trying to display multiple results from similar links with this function. Tried returning array with two variables $atlantic1 and $atlantic2 by adding the second link in $link2 and also tried creating another function with new short code for second result but nothing works.

What is the best way to solve this problem?

function fish($bubbles) {
    extract(shortcode_atts(array(
        "fin" => get_option('pacific'),
    ), $bubbles));


    $width = " width=\"".$fin['width']."\"";
    $height = " height=\"".$fin['height']."\"";
    $osorientation = " orientationMode=\"manual\"";
    
        
    $link = "https://pacific.local/item/1/A";   
    $path = parse_url($link, PHP_URL_PATH);
    $segments = explode('/', rtrim($path, '/'));
    
    wp_enqueue_script( 'some-pacific-js' ); 

    $atlantic = "<fish-info fAdd=\"".$segments[2]."\" fId=\"".$segments[3]."\" network=\"".$network."\"></fish-info>";

    return $atlantic;
    
}
add_filter('widget_text', 'do_shortcode');
add_shortcode('pacific', 'fish');


Solution

  • The preferred way is pass link as a parameter of the shortcode, then call the shortcode two times with specific link.

    First of all, change the fish function:

    function fish($atts) {
        // Pay attention, I removed "extract" so $fin is now a key inside $atts
        $atts = shortcode_atts( array(
          'fin' => get_option('pacific'),
          'item' => 'CHOOSE_A_DEFAULT'
        ), $atts );
    
    
        $width = " width=\"".$atts['fin']['width']."\"";
        $height = " height=\"".$atts['fin']['height']."\"";
        $osorientation = " orientationMode=\"manual\"";
    
        
        $link = "https://pacific.local/item/" . $atts['item'];   
        $path = parse_url($link, PHP_URL_PATH);
        $segments = explode('/', rtrim($path, '/'));
    
        wp_enqueue_script( 'some-pacific-js' ); 
    
        $atlantic = "<fish-info fAdd=\"".$segments[2]."\" fId=\"".$segments[3]."\" 
        network=\"".$network."\"></fish-info>";
    
        return $atlantic;
    
    }
    

    In the widget where you are calling the short code, youhave probably something like this:

    [pacific]
    

    You have to change it into something like this:

    [pacific item="1/A"]
    [pacific item="2/B"]