サポート » 使い方全般 » アドミンバーでループを使用したい

  • 解決済 d.w.c

    (@dwc-1)


    アドミンバーにカスタム投稿へのショートカットリストを追加したく、functions.phpに下記を追記しました。

    
    if (is_user_logged_in() ){
    function customize_admin_bar_menu($wp_admin_bar){
    
      global $post;
      $custom_list = get_posts(array(
      'post_type'   => 'custom',
      'numberposts' => -1,
      'order'       => 'asc',
      ));
      if($custom_list):
        $wp_admin_bar->add_menu(array(   //親
            'id'    => 'dashboard_custom',
            'meta'  => array(),
            'title' => sprintf(
                '<span class="ab-item">%s</span>',
                'カスタム投稿リスト'
            )
        ));
        
        $cnt='';
        foreach($custom_list as $post):
          setup_postdata($post);
          $cnt++;
          $wp_admin_bar->add_menu(array( //子
            'parent' => 'dashboard_custom',
            'id'     => 'dashboard_custom-'.$cnt,
            'meta'   => array(),
            'title'  => get_the_title(),
            'href'   => get_permalink()
          ));
        endforeach; wp_reset_postdata();
      endif;
      
    }
    add_action('admin_bar_menu', 'customize_admin_bar_menu', 9999);
    }

    functions内でのループの取得方法がよくわからないままとりあえず書いてみたらアドミンバー内は目的の動作をするようになりました。
    ただ、この状態ではダッシュボード内のカスタム投稿はもちろん、投稿や固定ページも各ページへのリンクをクリックするとURLは正常なのに表示内容がすべてカスタム投稿のループの最後のものにすり替わってしまいます。

    global $postのリセット方法が違うのか、そもそもループの取得方法が間違っているのか調べてもよくわかりませんでした。
    ループで取得した情報をアドミンバー内で完結させるにはどのように書けばいいんでしょうか?

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • global $postでは無理です。
    get_postsの結果から取得してください。

    if (is_user_logged_in() ){
    function customize_admin_bar_menu($wp_admin_bar){
    
      //global $post;
      $custom_list = get_posts(array(
      'post_type'   => 'custom',
      'numberposts' => -1,
      'order'       => 'asc',
      ));
      if($custom_list):
        $wp_admin_bar->add_menu(array(   //親
            'id'    => 'dashboard_custom',
            'meta'  => array(),
            'title' => sprintf(
                '<span class="ab-item">%s</span>',
                'カスタム投稿リスト'
            )
        ));
        
        $cnt='';
        foreach($custom_list as $post):
          //setup_postdata($post);
          $cnt++;
          $wp_admin_bar->add_menu(array( //子
            'parent' => 'dashboard_custom',
            'id'     => 'dashboard_custom-'.$cnt,
            'meta'   => array(),
            //'title'  => get_the_title(),
            //'href'   => get_permalink()
            'title'  => get_the_title( $post->ID ),
            'href'   => get_permalink( $post->ID )
          ));
        endforeach; //wp_reset_postdata();
      endif;
      
    }
    add_action('admin_bar_menu', 'customize_admin_bar_menu', 9999);
    }
    • この返信は6年、 2ヶ月前にmanboが編集しました。
    トピック投稿者 d.w.c

    (@dwc-1)

    とても分かりやすい修正を入れていただいてありがとうございました!
    目的の動作ができました。

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • トピック「アドミンバーでループを使用したい」には新たに返信することはできません。