サポート » 使い方全般 » ショートコード挑戦 初心者です

  • 解決済 iguigu

    (@iguigu)


    以下のコードをショートコードにしたいのですが、うまくいきません。
    ご教授お願いいたします

    <?php
    $pages = get_pages('child_of=52');
    foreach($pages as $page):
    if(has_post_thumbnail($page->ID)) {
    ?>
    <div class="item"><a href="<?php echo get_page_link($page->ID); ?>"><?php echo get_the_post_thumbnail( $page->ID,  'thumbnail', array('class' => 'img-responsive') ); ?></a>
    <h4><?php echo get_the_title($page->ID); ?></h4>
    <p></p>
    </div>
    <?php } endforeach; ?>
4件の返信を表示中 - 1 - 4件目 (全4件中)
  • function your_shortcode($atts) {
     $pages = get_pages('child_of=52');
     $content = '';
     foreach($pages as $page):
     if(has_post_thumbnail($page->ID)) {
        $content.='<div class="item"><a href="'. get_page_link($page->ID) .'">'. get_the_post_thumbnail( $page->ID,  'thumbnail', array('class' => 'img-responsive') ).'</a><h4>'. get_the_title($page->ID).'</h4><p></p></div>';
     } endforeach;
     return $content;
    }
    add_shortcode('your_sc', 'your_shortcode');

    こうですか?

    トピック投稿者 iguigu

    (@iguigu)

    すごい勉強になりました
    ありがとうございます
    上記を見マネして

    <?php query_posts('post_type=itemlist'); if(have_posts()):while(have_posts()):the_post(); ?>
    <div class="item"><a href="<?php the_permalink() ?>"><h3><?php the_title(); ?></h3>
    <?php the_post_thumbnail('item_thum',array('class' => 'img-responsive')); ?>
    
    <p><?php echo mb_substr(get_the_excerpt(), 0, 30); ?></p></a></div>
    <?php endwhile; endif; wp_reset_query(); ?>

    function getcosmeList($atts){
    	$content = '';
    	query_posts('post_type=itemlist');
    	if(have_posts()):
    	while(have_posts()):
    	the_post();
    	$content.='<div class="item"><a href="'. the_permalink() .'"><h3>'. the_title() .'</h3>'. the_post_thumbnail('item_thum',array('class' => 'img-responsive')) .'<p>'. mb_substr(get_the_excerpt(), 0, 30) .'</p></a></div>';
    	endwhile; endif;
    
    return $content;
    }
    add_shortcode("cosmelist","getcosmeList");

    したのですが、aタグ反映されず、URLが文字列として出てしまいます。。。
    なにか間違っているのでしょうか??

    the_fooのような名前の関数は基本的に文字列を返すのではなく出力します
    一部を除いてテンプレート関数にはgetから始まる名前の関数があるはずです。(get_permalink,get_the_post_thumbnail)

    ショートコードは返り値を本文に挿入するのでこちらを使う必要があります。

    トピック投稿者 iguigu

    (@iguigu)

    違いがわかっていませんでした。。
    get_にすることで正しく表示できました。
    ありがとうございます!

4件の返信を表示中 - 1 - 4件目 (全4件中)
  • トピック「ショートコード挑戦 初心者です」には新たに返信することはできません。