Advertisement
Guest User

Untitled

a guest
May 17th, 2018
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.06 KB | None | 0 0
  1. <?php
  2. /*
  3. Topic: https://ja.wordpress.org/support/topic/投稿記事内に固定ページを挿入することは可能で/
  4. Description: 投稿記事内に固定ページを挿入することは可能でしょうか(コメントを含む)
  5. Author: https://ja.forums.wordpress.org/profile/13907727
  6. */
  7.  
  8. add_shortcode( 'mypage', 'my_insert_page_with_comments' );
  9.  
  10. function my_insert_page_with_comments( $atts ) {
  11.   $atts = shortcode_atts( array(
  12.       'id'    => '',  // 固定ページのID (スラッグより優先)
  13.       'slug'  => '',  // 固定ページのスラッグ
  14.       'count' => 5    // 表示するコメントの最大数
  15.     ),
  16.     $atts );
  17.  
  18.   $mypage = NULL;
  19.   if ( $atts['id'] )  // IDが指定されていたら
  20.     $mypage = get_post( $atts['id'] );  // IDで固定ページを取得
  21.   elseif ( $atts['slug'] )  // スラッグが指定されていたら
  22.     $mypage = reset( get_posts( array(
  23.       'name'      => $atts['slug'],  // スラッグで
  24.       'post_type' => 'page'          // 固定ページを取得
  25.     ) ) );
  26.   if ( empty( $mypage ) )  // 見つからなかった
  27.     return '指定された固定ページが見つかりません。';
  28.  
  29.   $s = '<div>固定ページここから';  // ショートコードを展開した結果
  30.  
  31.   // 固定ページへジャンプするリンクを取得
  32.   $link = get_page_link( $mypage->ID );
  33.   $s .= "<div>";
  34.   $s .= "ジャンプ: <a href=\"{$link}\">{$mypage->post_title}</a>";
  35.   $s .= '</div>';
  36.  
  37.   // 固定ページの本文を取得
  38.   $s .= '<hr /><div>';
  39.   $s .= wpautop( do_shortcode( $mypage->post_content ) );
  40.   $s .= '</div><hr />';
  41.  
  42.   // 固定ページのコメントを取得
  43.   $comments = get_comments( array(
  44.     'number'  => $atts['count'],  // 表示するコメントの最大数
  45.     'post_id' => $mypage->ID
  46.   ) );
  47.   // コメントをフォーマットして取得
  48.   $comments = wp_list_comments( array( 'echo' => false ), $comments );
  49.   $s .= $comments;
  50.  
  51.   $s .= '固定ページここまで</div>';  // ショートコードを展開した結果
  52.   return $s;
  53. }
  54. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement