是否可以使用HTML结束标记启动WordPress短代码?

时间:2017-05-01 15:44:01

标签: php html wordpress shortcode

我试图创建一个自定义WordPress短代码来打破"打破"进入我创建的页面容器,这样我就可以在页面布局的自然流程中显示 true 全宽图像。我的问题是,WordPress似乎并没有尊重我使用结束HTML标记开始输出的事实。

我的页面布局在正常情况下使用.width-container来提供最大宽度和一些填充装订线。

<div class="width-container">
    <h2>Title</h2>
    <p>...</p>
    <p>...</p>

    <img src="" alt="">
    <p>...</p>
    <p>...</p>
</div>

使用此短代码时我想要首先关闭 .width-container包装器,在包装器外插入一些额外的标记,然后重新打开一个新的.width-container ,例如:

<div class="width-container">
    <h2>Title</h2>
    <p>...</p>
    <p>...</p>

<!-- shortcode -->
</div>

<div class="fullwidth-wrapper">
    <img src="" alt="">
</div>

<div class="width-container">
<!-- /shortcode -->

    <img src="" alt="">
    <p>...</p>
    <p>...</p>
</div>

我尝试使用关闭和非关闭的短代码,我尝试过使用ob_start() / ob_get_contents() / ob_end_clean(),似乎每个组合我都可以考虑到。我已经尝试了echo,将其作为HTML字符串保存到var中,这样我就可以返回输出了,我还测试了这个跨浏览器,看看这是否是浏览器的干扰。每次尝试,我都会得到以下内容:

<div class="width-container">
    <h2>Title</h2>
    <p>...</p>
    <p>...</p>

<!-- shortcode -->
<div class="fullwidth-wrapper">
    <img src="" alt="">
</div>

    <div class="width-container"> <!-- this is now incorrectly double nested -->
<!-- /shortcode -->

        <img src="" alt="">
        <p>...</p>
        <p>...</p>
    </div>
</div>

这会导致.width-container的双重嵌套,这不是理想的效果。

我的functions.php短代码:

/**
 * [fullwidth]
 * Custom shortcode to handle full-width images
 */
function full_width_image( $atts ) {
    $a = shortcode_atts( array(
        'src' => 'http://placehold.it/2000x900?text=Placeholder+Image',
        'alt' => 'Full Width Image Alt Text'
    ), $atts);

    ob_start();
    ?>
    </div>
    <div class="fullwidth-image-wrapper">
        <img class="fullwidth-image" src="<?php echo $a["src"]; ?>" alt="<?php echo $a["alt"]; ?>">
    </div>
    <div class="width-container">
    <?php

    $output = ob_get_contents();
    ob_end_clean();

    return $output;
}
add_shortcode( 'fullwidth', 'full_width_image' );

WordPress Shortcode API没有多大帮助,因为在盯着页面太长时间之后,我无法特别提及我正在尝试的内容,也没有上述内容。卫生/处理HTML。 有没有办法用HTML结束标记开始短代码?

1 个答案:

答案 0 :(得分:0)

以下代码可实现您正在寻找的内容。

使用:[全宽]在此插入图像标记[/ fullwidth]

function full_width_image( $atts, $content = null ) {
    return '</div> <div class="fullwidth-wrapper">' . $content . '</div> <div class="width-container">';
}
add_shortcode( 'fullwidth', 'full_width_image' );

返回最初返回a以关闭之前的div,然后创建新div以包装图像。之后它会中断以允许您将图像添加为短代码之间的内容。然后它关闭div然后打开一个新的。

您的示例显示变量已分配图像src和alt。但是,此选项允许更大的灵活性,因为您可以在任何给定时间在空间中添加任何图像。

相关问题