WP - 简码包括 html 和 php 的混合(ACF 变量)

WP - shortcode including a mixture of html and php (ACF variables)

我正在尝试创建一个包含 html 和 php 的 WP 简码。例如,类似的东西(那是行不通的):

function my_first_shortcode() {
    $content = <<<EOT
    <h1>Some title</h1>
    <p><?php the_field('description'); ?></p>
EOT;
return $content; 
} 
add_shortcode('my_shortcode', 'my_first_shortcode');

the_field('name_of_field');通常输出指定variable/field(高级自定义字段)的内容。

HEREDOC 方法是否正确?如果是这样,我该怎么做?如果我可以将变量传递给短代码,那也很棒。

谢谢

我总是喜欢为我的简码使用输出缓冲,如下例。

function my_first_shortcode() {
    ob_start(); ?>
    <h1>Some title</h1>
    <p><?php echo the_field('description'); ?></p>
    <?php
    return ob_get_contents();
} 
add_shortcode('my_shortcode', 'my_first_shortcode');

首先,您不能在 HEREDOC 中写入 PHP 标签。 你可以这样使用它:

$the_field = 'the_field';
$content = <<<EOT
<h1>Some title</h1>
<p>{$the_field('description')}</p>
EOT;

要将属性传递给短代码,这非常简单。 例如我们有简码:

[my_shortcode att_1="some_value" att_2="some_value"]

function my_first_shortcode($atts)
{
    $att_1 = $atts['att_1'];
    $att_2 = $atts['att_2'];
}
add_shortcode('my_shortcode', 'my_first_shortcode');
add_shortcode('location_start_your_application_group', 'start_your_application_group');

function start_your_application_group() {
    ob_start();

    $start_your_application_group = '';
    $start_your_application_group .= '<section class="start-your-application">';
     if ( have_rows( 'start_your_application_group', 'option' ) ) : 
         while ( have_rows( 'start_your_application_group', 'option' ) ) : the_row(); 
           $heading = get_sub_field( 'heading' );
             $content = get_sub_field( 'content' );

             if ( $heading !== '' ) {
                    $start_your_application_group .= '<h3 class="start-your-application__heading">' . $heading . '</h3>';
             }
             if ( $content !== '' ) {
                $start_your_application_group .= '<div class="start-your-application__content">' . $content . '</div>';
             }

             $image = get_sub_field( 'image' );
             if ( $image ) { 
                $start_your_application_group .= '<div class="start-your-application__image-container"><img class="start-your-application__image" src="' . esc_url($image['url']) .'" alt="' . $image['alt'] . '" /></div>';
            } 
        endwhile;
    endif;

    $start_your_application_group .= '</section>';
    $start_your_application_group = ob_get_clean();

    return $start_your_application_group;
}