Wordpress短代码 - 第一个短代码被破坏

时间:2018-04-22 09:41:47

标签: php wordpress hyperlink shortcode

我有一个页面,我想在计划页面添加一些音乐会。 为了做到这一点,我决定使用短代码,这样用户就可以提供必要的数据,我将解析它并在短代码函数中生成html。

首先,我想告诉你为什么我认为这与wordpress相关。我已将此代码直接添加到页面php文件中:

<h4>This year hardcoded</h4>
<a href='#' class='p-link'>
    <h2>01.02.2018 / RHCP</h2>
    <p>20:00 / NY</p>
</a>
<a href='#' class='p-link'>
    <h2>03.04.2018 / The Rolling Stones</h2>
    <p>21:00 / LONDON</p>
</a>
<a href='#' class='p-link'>
    <h2>11.12.2018 / Pink Floyd</h2>
    <p>22:00 / TOKIO</p>
</a>

它工作正常。

enter image description here

由于我的短代码函数返回相同的我预期相同的结果,但我没有得到它。第一个短代码结果被破坏了。

这是我添加到functions.php中的内容:

function shortcode_issue_func( $atts ) {
    $shortcode_atts = shortcode_atts( array(
        'date' => '',
        'time' => '',
        'title' => '',
        'location' => '',
        'link' => '#'
    ), $atts );

    $html = "<a href='{$shortcode_atts['link']}' class='p-link'>
                <h2>{$shortcode_atts['date']} / {$shortcode_atts['title']}</h2>
                <p>{$shortcode_atts['time']} / {$shortcode_atts['location']}</p>
            </a>";
    return $html;
}
add_shortcode( 'shortcode-issue', 'shortcode_issue_func' );

在wordpress页面编辑中,我添加了这个:

[shortcode-issue date="19.07.2018" time="20:00" title="RHCP" location="NY" link="http://localhost/wordpress/rep-3/" ]
[shortcode-issue date="21.08.2018" time="21:00" title="The Rolling Stones" location="London" link="http://localhost/wordpress/rep-3/" ]
[shortcode-issue date="23.11.2018" time="22:00" title="Pink Floyd" location="NY" link="http://localhost/wordpress/rep-3/" ]

这是输出

enter image description here

您可以注意到第1部分和第2部分未在“a”标记中包装在一起,因为第3部分是。

在返回之前转储$ html,显示应该没有问题:

enter image description here

我做的hacky解决方案是在“a”标记之前添加空的“p”标记。

$html = "<p style='display: none;'></p>
        <a href='{$shortcode_atts['link']}' class='p-link'>
            <h2>{$shortcode_atts['date']} / {$shortcode_atts['title']}</h2>
            <p>{$shortcode_atts['time']} / {$shortcode_atts['location']}</p>
        </a>";
return $html;

enter image description here

但是我不想在我的代码中遇到这样的黑客攻击,我找不到发生这种情况的原因。 如果有人可以提供帮助,我会非常感激。

编辑1

代码包含HTML5声明 - &gt; <!DOCTYPE html>

所以应该允许“a”标签包装。

编辑2

我刚注意到生成的html中有一个“幻影”“p”标签。

enter image description here

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试删除$html变量值中的额外空格

所以改变这个:

$html = "<a href='{$shortcode_atts['link']}' class='p-link'>
            <h2>{$shortcode_atts['date']} / {$shortcode_atts['title']}</h2>
            <p>{$shortcode_atts['time']} / {$shortcode_atts['location']}</p>
        </a>";

..对这一个:

$html = "<a href='" . esc_url( $shortcode_atts['link'] ) . "' class='p-link'>" .
    "<h2>{$shortcode_atts['date']} / {$shortcode_atts['title']}</h2>" .
    "<p>{$shortcode_atts['time']} / {$shortcode_atts['location']}</p>" .
"</a>";

PS:esc_url()一个URL地址始终是一个好习惯。

相关问题