2016-07-16 11 views
0

私が取り組んでいるこのショートコードでは、いくつかのことがあります。これについての私の知識は最高ではありませんが、私は学びたいと思っています。WordPress - CPTを出力するショートコードを作成する方法

/** 
* 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"]$argsをユーザーが修正するのは簡単です。もう1つは動作していないのは、私がやろうとしている背景のURLです。フロントエンドでは、バックグラウンドのURLを除いてすべてが出力されています。

答えて

0

問題がある場合は、使用後に変数$featured_imgを作成するという問題があります。それはwhileループにあるはずです。

これは甘い、私は背景IMGを取得することができます

/** 
* 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'); 
+0

このコードを試してみてください!どのように私は短いコードのattsとして使用することができますパラメータを抽出することができますか? –

+0

まず、 '$ atts'パラメータをshortcode関数に追加すると、' $ atts ['example_attribute'] 'のように使うことができます。上記のコードを編集したので、簡単に使用できます。 –

関連する問題