WordPress - 如何创建输出CPT的短代码

时间:2016-07-16 16:52:14

标签: wordpress shortcode

我正在处理的这些短代码中有一些我想做的事情。我对此的了解并不是最好的,但我正在努力学习。

/**
 * Recent Project Shortcode
 */
function project_query() {
    $args = array(
        'posts_per_page' => 1,
        'post_type'      => 'projects',
        'order'          => 'ASC',
    );
    $projects_query = new WP_Query( $args );
    if ( $projects_query->have_posts() ) :
        // var_dump(the_post_thumbnail_url("full")); exit;
        $html_out = '<article class="recent-project" style="background: url(' . $featured_img . ') no-repeat center center; background-size: cover;">';
        while ( $projects_query->have_posts() ) :
            $projects_query->the_post();
            // Do stuff with each post here

            $title = get_the_title();
            $link = get_the_permalink();
            $featured_img = get_the_post_thumbnail_url( $post->ID, 'full' );

            $html_out .= '<h5>Latest Project</h5>' . '<h2>' . $title . '</h2>' . '<a class="btn btn-lg btn-tertiary" href="' . $link . '">' . 'Discover' . '</a>';
        endwhile;
        $html_out .= '</article>';
    else : // No results
        echo "Nothing to show";
    endif;
    wp_reset_query();
    return $html_out;
}
add_shortcode( 'show_project', 'project_query' );

这里有一些问题。什么工作是在前端它拉出项目名称,这是甜蜜的,按钮链接到适当的页面。

以下是我喜欢使用短信代码的方式:[show_projects posts_per_page="3" order="ASC"]我想让它变得简单&#34;简单&#34;供用户修改$args。第二件不起作用的是我尝试做的背景网址。现在在前端,一切都在输出,除了背景网址。

1 个答案:

答案 0 :(得分:0)

嘿Darren问题是你在使用它后创建了$featured_img变量。它应该在while循环中。

请尝试此代码

/**
 * Recent Project Shortcode
**/
function project_query($atts) {
    $atts = shortcode_atts(
        array(
            'example_attribute' => 'example_value',
        ),
        $atts, 'example'
    );

    //if you want to use the attribute you should use $atts['example_attribute'] for example

    $args = array(
        'posts_per_page' => 1,
        'post_type'      => 'projects',
        'order'          => 'ASC',
    );
    $posts = get_posts( $args );
    if ( !empty( $posts ) ) :
        $post = array_shift( $posts );
        $title = get_the_title($post->ID);
        $link = get_the_permalink($post->ID);
        $featured_img = get_the_post_thumbnail_url( $post->ID, 'full'     );

        $html_out = '<article class="recent-project" style="background: url(' . $featured_img . ') no-repeat center center; background-size: cover;">';
           // Do stuff with each post here

        $html_out .= '<h5>Latest Project</h5>' . '<h2>' . $title . '</h2>' . '<a class="btn btn-lg btn-tertiary" href="' . $link . '">' . 'Discover' . '</a>';
        $html_out .= '</article>';
     else : // No results
        echo "Nothing to show";
     endif;

     return $html_out;
}
add_shortcode( 'show_project', 'project_query' );