Wordpress 简码 - 第一个简码被破坏

Wordpress shortcodes - first shortcode is broken

我有一个页面,我想在其中添加一些音乐会到日程表页面。 为此,我决定使用简码,这样用户就可以只提供必要的数据,我将解析它并在简码函数中生成 html。

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

<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>

而且效果很好。

因为我的简码函数 return 相同,所以我期望得到相同的结果,但我没有得到。第一个短代码结果已损坏。

这是我添加到 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/" ]

这是输出

您会注意到第 1 部分和第 2 部分没有像第 3 部分那样包含在 "a" 标记中。

在 return 之前转储 $html,表明应该没有问题:

我做的 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;

但我不想在我的代码中出现这样的 hack,而且我找不到发生这种情况的原因。 如果有人能提供帮助,我将不胜感激。


编辑 1

代码有 HTML5 声明 --> <!DOCTYPE html>

所以应该允许 "a" 标签换行。


编辑 2

我刚刚注意到结果 html.

中有一个 "phantom" "p" 标签


谢谢!

尝试删除$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 地址始终是一个好习惯。