Nested Code Snippets

时间:2020-10-27 作者:matt93

我是wordpress的新手,我正在努力实现以下目标:

I have a custom type albums seeded by a plugin and I would like to display this data in a list.

我安装了Code Snippets Plugin 并能够创建以下工作短代码:

function display_albums_shortcode() {
    $query = new WP_Query(
        array(
            \'post_type\' => \'albums\'
        ));
        
    $output = \'<section>\';

    if ($query->have_posts()):
        while ( $query->have_posts() ):
            $album = $query->the_post();
            $output .= \'<div><figure>\' . get_the_title($album) . \' </figure></div>\';
        endwhile; 
    endif;
    
    $output .= \'</section>\';

    wp_reset_postdata();

    return $output;
}

add_shortcode(\'display_albums\', \'display_albums_shortcode\');
然而,我想让它模块化一点。我希望有一个名为render\\u album\\u list\\u item的独立函数(代码段),它接受album 作为参数,并返回HTML:

function render_album_list_item($album) {
    $output = \'<div><figure>\' . get_the_title($album) . \' </figure></div>\';
    return $output;
}
随后,我想在第一个代码段中调用render\\u album\\u list\\u item,类似于:

function display_albums_shortcode() {
    $query = new WP_Query(
        array(
            \'post_type\' => \'albums\'
        ));

    $output = \'<section>\';

    if ($query->have_posts()):
        while ( $query->have_posts() ):
            $album = $query->the_post();
            $output .= render_album_list_item($album);
        endwhile; 
    endif;

    $output .= \'</section>\';

    wp_reset_postdata();

    return $output;
}

add_shortcode(\'display_albums\', \'display_albums_shortcode\');
不幸的是,我无法使上面的代码片段工作,并且在文档中没有找到任何内容。

此外:is this the only way how to display the data - by manually creating a HTML string? 来自ReactJS的世界,这种方法非常糟糕。如有任何想法和建议,将不胜感激!

谢谢

1 个回复
SO网友:matt93

我通过创建one code snippet:

function render_album_list_item($album) {
    $output = \'<div><figure>\' . get_the_title($album) . \' </figure></div>\';
    return $output;
}

function display_albums_shortcode() {
    $query = new WP_Query(
        array(
            \'post_type\' => \'albums\'
        ));

    $output = \'<section>\';

    if ($query->have_posts()):
        while ( $query->have_posts() ):
            $album = $query->the_post();
            $output .= render_album_list_item($album);
        endwhile; 
    endif;

    $output .= \'</section>\';

    wp_reset_postdata();

    return $output;
}

add_shortcode(\'display_albums\', \'display_albums_shortcode\');
不过,这是the best way 为了实现这个目标?