创建简码

Creating a shortcode

我正在尝试创建一个我已经完成的 1:1 的 gird,但必须有更简洁的方法。我将每天编辑此文本和图像,因此需要它整洁且易于确定什么是什么...这是我到目前为止所做的,这远非理想...

我想通过短代码来完成,但我不确定如何处理它。也许这里有人可以帮助我?

 // Add Shortcode
function AdvisoryFunc( $atts ) {

    // Attributes
    $atts = shortcode_atts(
        array(
            'text' => 'text',
            'image' => 'IMG',
        ),
        $atts,
        'AdvisoryTag'
    );

}
add_shortcode( 'AdvisoryTag', 'AdvisoryFunc' );

你可以这样做:

function AdvisoryFunc( $atts, $content = null ) {
    $a = shortcode_atts( array(
        'image' => '',
    ), $atts );

    return '
        <div class="section-group">
            <div class="col-1">' . $content . '</div>'
            <div class="col-2"><img src="' . $a['image'] . '"></div>
        </div><!-- /section-group -->';
}

add_shortcode( 'AdvisoryTag', 'AdvisoryFunc' );

然后你会像这样使用它:

[AdvisoryTag image="http://www.examplesite.com/wp-content/uploads/2018/07/image.jpg"]Your html content goes here[/AdvisoryTag]

您必须调整 return 语句中的 HTML 以匹配您的 HTML 结构(类 和图像属性),但这应该会让您更漂亮即将完成。

一个更简单的选择是使用更简单的网格,方法是在您的外观 > 自定义 > 附加 CSS 部分中粘贴一些 CSS 像这样:

@media (min-width: 768px){
    .grid { width: 100%; display: table; table-layout: fixed; }
    .grid > * { display: table-cell; }
}

这样您就可以在自己的页面上执行以下操作

<div class="grid">
    <div>Text</div>
    <img src="/path/to/img" />
</div>

或者,您可以考虑使用自定义 Post 类型,或者使用 CPT API or a plugin like the widely used CTP UI plugin. From there you could make a Post Type Template or a Page Template 从最近的 post 中提取内容和特色图片。老实说,这可能是我在你的鞋子里做的,因为它会为 updating/managing 状态提供更容易的途径,并提供以前状态的记录,代价是多一点 "set up" 时间。


最后,如果您只想使用简码,可以使用如下内容:

add_shortcode( 'advisory_tag', function( $atts ){
    extract( shortcode_atts( array(
        'text'  => 'Placeholder Text',
        'image' => '/placeholder/image.jpg'
    ), $atts ) );

    ob_start(); ?>

    <div class="section group">
        <div class="col span_1_of_2"><?= $text; ?></div>
        <div class="col span_1_of_2">
            <a href="<?= $image; ?>" target="_blank" title="Click to Enlarge" rel="noopener" style="outline: none;">
                <img src="<?= $image; ?>" alt="Advisory Image for <?= date( 'l, F jS, Y' ); ?>" />
            </a>
        </div>
    </div>

    <?php $ob = ob_get_contents();
    ob_end_clean();

    return $ob;
});

然后您只需将 [advisory_tag text="Some Text Here" image="link/to/image.jpg"] 放入 post,然后根据需要更新