phpwordpress

PHP / Wordpress creating a shortcode as a string


I'm trying to write a shortcode, but it has quotes within quotes within quotes because it has a shortcode in it. This link is breaking and not rendering the href correctly. Here:

<?php
function worksheet($atts){
    $default = array(
        'year' => 'Year-1',
        'title' => 'Writing Numbers',
        'level' => 'Easy',
    );
    $attributes = shortcode_atts($default, $atts);
    
    return "<a href='[s2File download='access-s2member-ccap-free/" . $attributes['year'] . "/" . $attributes['title'] . ".pdf' download_key='true' /]&s2member_file_inline=yes'>" . $attributes['title'] . " (" . $attributes['level'] . ")</a>";
    }
add_shortcode('worksheet', 'worksheet');
  
?>

I've read the other solutions about escaping th quotation marks but it still doesn't work with the following code:

<?php
function worksheet($atts){
    $default = array(
        'year' => 'Year-1',
        'title' => 'Writing Numbers',
        'level' => 'Easy',
    );
    $attributes = shortcode_atts($default, $atts);
    
    return "<a href=\"[s2File download='access-s2member-ccap-free/" . $attributes['year'] . "/" . $attributes['title'] . ".pdf' download_key='true' /]&s2member_file_inline=yes\">" . $attributes['title'] . " (" . $attributes['level'] . ")</a>";
    }
add_shortcode('worksheet', 'worksheet');
  
?>

I'm expecting the same as if I just write the link as follows:

<a href="[s2File download='access-s2member-ccap-free/Year-1/Counting with 10 pence (A).pdf' download_key='true' /]&s2member_file_inline=yes">TEST LINK</a>

I've also tried to use " . chr(39) . ", replacing the quotes. DOesn't work. I have read all the other solutions.


Solution

  • Your code looks mostly correct, but there’s a small issue in how the link is generated with the [s2File] shortcode within your worksheet function. WordPress doesn’t automatically parse shortcodes embedded in href attributes, so using do_shortcode is necessary to ensure that the [s2File] shortcode is processed properly. Here's an updated version of your code that should work as expected:

    function worksheet($atts) {
       $default = array(
           'year' => 'Year-1',
           'title' => 'Writing Numbers',
           'level' => 'Easy',
      );
      $attributes = shortcode_atts($default, $atts);
    
      $s2file_shortcode = "[s2File download='access-s2member-ccap-free/".$attributes['year']."/".$attributes['title'].".pdf' download_key='true' /]&s2member_file_inline=yes";
      $link = do_shortcode($s2file_shortcode);
    
      return "<a href=\"".$link."\">".$attributes['title']." (".$attributes['level'].")</a>"; } 
    }
    
    add_shortcode('worksheet', 'worksheet');
    

    This update uses do_shortcode to process the [s2File] shortcode, ensuring the proper URL is generated and placed within the href attribute.