Shortcode with parameters inside parameters

I have a repetitive sentence throughout my site with different parameters.

Example: NAME read a book on DAY | TITLE

where the capitalized words vary with each post and (here’s the kicker) I want DAY to be a link – one of seven individual links (one for each day of the week).

I have seven shortcodes for the links with each day of the week and a shortcode for the sentence but I can’t quite get them to work together.

function books($atts, $content = null) {
extract(shortcode_atts(array(
    "name" => '',
    "day" => '',
    "title" => '',
), $atts));
$output="<div class="cite">";
if($name) { $output .= ''.$name.' read a book';}
if($day) { $output .= ' on '.do_shortcode($content).'';}
$output .= ' | '.$title.'</div>';
    return $output;
}
add_shortcode("books", "books");

And then the code for the days of the week is pretty straight forward:

function monday() {        
return '<a href="http://website.com/" target="_blank">Monday</a>'; 
}
add_shortcode("monday", "monday");

In my post

[books name="Mary Sue" title="See Jane Run"]

works just fine and outputs: Mary Sue read a book | See Jane Run

but

[books name="Mary Sue" title="See Jane Run" day="[monday]"]

goes wonky and outputs: “Mary read a book on | “See

I feel like I may be approaching the problem wrong, but am not sure how else to go about defining several different variables in each post and keep the consistency and simplicity of reusing the same text.

1 Answer
1

The days of the week shortcodes aren’t needed. Also, the way you’re trying to use them isn’t allowed. Why not just use the title and do what you want in the books shortcode?

function books($atts, $content = null) {
  $atts = shortcode_atts( [
    "name" => '',
    "day" => '',
    "title" => '',
  ], $atts );

  $atts[ 'day' ] = ucfirst( strtolower( $atts[ 'day' ] ) );

  //* If you want to change the URL, you could switch on the day
  switch( $atts[ 'day' ] ) {
    case 'Monday':
      $url="https://example.com/";
      break;
    case 'Tuesday':
      $url="https://someotherurl.com/";
      break;
    //* etc.
  }

  return sprintf( 
    '<div class="cite">%1$s%2$s | %3$s</div>',
    '' === $atts[ 'name' ] ? '' : $atts[ 'name' ] . ' read a book',
    '' === $atts[ 'day' ] ? '' : 
      sprintf( ' on <a href="https://wordpress.stackexchange.com/questions/296007/%1$s" target="_blank">%2$s</a>', $atts[ 'day' ], $url ),
    $atts[ 'title' ]
);

Leave a Comment