wordpress短代码可以包含条件语句吗?

时间:2014-05-18 21:44:45

标签: wordpress shortcode

我正在使用wordpress高级自定义字段(acf)插件。我正在尝试制作一个短代码,用于显示最新的博客文章,我想通过if else检索两个 acf 字段值条件逻辑。但我不能使用 if else 语句来获取此短代码。当我将此代码粘贴到functions.php中时,我的网站显示一个空白页面,其中显示错误消息意外如果问题。请参阅问题专栏。

代码:

function latest_shortcode($atts)
{
    extract( shortcode_atts( array(
    'title' => '',
    'category' => ''
), $atts, 'latest' ) );

    $q = new WP_Query(
        array('posts_per_page' => '6', 'post_type' => 'post'));

    // Get the ID of a given category
    $category_id = get_cat_ID( ''.$category.'' );

    // Get the URL of this category
    $category_link = get_category_link( $category_id );

    $list = '<div class="fix single_home_content">
            <div class="fix single_home_content_container">
            <h2><i class="fa fa-angle-double-down"></i> '.$title.' <a href="'.esc_url( $category_link ).'">See all <i class="fa fa-angle-double-right"></i></a></h2>';

    while($q->have_posts()) : $q->the_post();

        //get the ID of your post in the loop
        $id = get_the_ID();
    $downloadlink = get_field('downloadlink');
        $downloadfile = get_field( "downloadfile" );

        $post_thumbnail=  get_the_post_thumbnail( $post->ID, 'apps-img' );      
        $list .= '

        <div class="fix single_content floatleft">
        <a href="'.get_permalink().'">'.$post_thumbnail.'</a>
        <h2><a href="'.get_permalink().'">'.ShortenText(get_the_title()).'</a></h2>
        <div class="rating">
            '.kk_star_ratings($pid).'
        </div>
        <div class="home_download">
            <a href="'.if($downloadlink){$downloadlink}else{$downloadfile}.'">Download</a>
        </div>
    </div>
        ';        
    endwhile;
    $list.= '</div></div>';
    wp_reset_query();
    return $list;
}

add_shortcode('latest', 'latest_shortcode');

我无法在上面的代码中找到这一行。

<a href="'.if($downloadlink){$downloadlink}else{$downloadfile}.'">Download</a>

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

我猜这一行会导致语法错误......

<a href="'.if($downloadlink){$downloadlink}else{$downloadfile}.'">

尝试改为......

<a href="'.(($downloadlink)?$downloadlink:$downloadfile).'">

另外......这条线..

$category_id = get_cat_ID( ''.$category.'' );

应该是

$category_id = get_cat_ID($category);

无需引号/连接