简码不返回两个相同的属性

问题描述

因此由于某些原因,我无法提取相同的链接属性并将其传递到我的代码中。

这是简码:

[slide headline="<h2>Title</h2>" image="https://via.placeholder.com/150" body="The text in the body" link="Test1|https://www.test1.com" link="Test2|https://test2.com"]

var_dump($atts)仅返回一个链接,如下所示:

array (size=4)
  'headline' => string '</p>
<h2>Title</h2>
<p>' (length=29)
  'image' => string 'https://www.raritanheadwaters.org/wp-content/uploads/2018/01/placeholder-picture-large-opt.png' (length=94)
  'body' => string 'The text in the body' (length=202)
  'link' => string 'Test1|https://www.test1.com' (length=61)

这是我的代码

function slide_item_shortcode($atts,$content = null)
{
    shortcode_atts([
            "image" => '',"headline" => '',"body" => '',"link" => '',],$atts);

    var_dump($atts);

    $social_links = explode("|",$atts['link']);

    return '<li class="slide">
            <p><img src="' . esc_url($atts['image']) . '" alt="" /></p>
            <p>'. $atts['headline'] .'</p>
            <p>'. $atts['body'] .'</p>
            <p>'. '<a href="' . $social_links[1] . '" target="_blank">' . $social_links[0] . '</a>' .'</p>
            </li>';
}
add_shortcode('slide','slide_item_shortcode');

解决方法

您可以通过对其他角色使用额外的爆炸来传递多个链接

[slide ... links="Test1|https://www.test1.com,Test2|https://www.test2.com"]
function slide_item_shortcode($atts,$content = null)
{
    shortcode_atts([
        "image" => '',"headline" => '',"body" => '',"links" => '',],$atts);
    
    $linkPairs = explode(',',$atts['links']); // separate the pairs
    $output = '<li class="slide">';
    
    foreach($linkPairs as $linkPair) {
        $pair = explode('|',$linkPair); // separate the title and url
        $output .= 
            '<p><img src="' . esc_url($atts['image']) . '" alt="' . $pair[0] .'" /></p>
             <p>'. $atts['headline'] .'</p>
             <p>'. $atts['body'] .'</p>
             <p>'. '<a href="' . $pair[1] . '" target="_blank">' . $pair[0] . '</a>' .'</p>';
    }

    $output .= '</li>';
    
    return $output;
}
,

我建议您不要在html内部属性中使用html,而是为该属性创建另一个将覆盖默认值的属性,我还为示例链接添加了另一个参数:

简码:

[myshortcode heading="Text of heading" heading_tag="h3" links="Name of link 1|#url1|blank,Name of Link2|#url2"]

和处理程序本身

function linkParser($source) {
  $args = array_map('trim',explode('|',trim($source)));
  $keys = ['url_name','url','target'];
  $results = [];
  foreach($args as $key => $value) {
    $results[(isset($keys[$key]) ? $keys[$key] : $key)] = $value;
  }
  return $results;
}
function myShortCode($attrs,$content = null) {
  $attrs = shortcode_atts([
    'heading_tag' => 'h2',"heading" => "","links" => ""
  ],$attrs);

  $heading = sprintf('<%1$s>%2$s</%1$s>',(!empty($attrs['heading_tag']) ? $attrs['heading_tag'] : 'h2'),$attrs['heading']);

  $links = [];
  if(!empty($attrs['links'])) {
    $links = array_map('linkParser',explode(',$attrs['links']));
  }

  // Tests with kint debug
  d($heading);
  d($links);
}

add_shortcode('myshortcode','myShortCode');

enter image description here