LoginSignup
0
0

More than 3 years have passed since last update.

WordPressで投稿者アーカイブページも検索に引っかかるようにしたい

Posted at

顧客から受け継いだサイトで、投稿者アーカイブページを検索に引っ掛けたい、という要望がありました。

functions.php

//店舗情報を格納するポストタイプを追加
//検索に引っ掛ける為。
/*============================================== */
function create_shop_post_type() {

  register_post_type( 'shop',  // カスタム投稿名
    array(
      'label' => '店舗情報',  // カスタム投稿ラベルを検索結果に出す為ラベルを設定
      'public' => true,  //検索結果に出す為PublicはTrue
      'has_archive' => false,
      'show_ui' => false,  //管理画面UI不要
      'rewrite' => false,   //URIのリライト不要
    )
  );
}
add_action( 'init', 'create_shop_post_type' );

functions.php

// 説明:作成したカスタム投稿SHOPへのリンクを全て投稿者アーカイブに
/*============================================== */
function modify_shop_post_link($permalink){
    global $post;
    if($post->post_type === 'shop'){
        $permalink = get_author_posts_url( $post->post_author );
    }
    return $permalink;
}
add_filter('the_permalink','modify_shop_post_link');

functions.php
//既存のユーザーに基づいてカスタム投稿SHOPを作成
//※一回だけ実行
/*============================================== */
function create_post_for_shopuser() {
  $shops = get_users( array(
    'role__in' => array( 'editor' ),
    'orderby' => 'nicename',
    'order' => 'ASC',
  ) );
  foreach ($shops as $shop) {
    $shop_name = get_field( 'shop_name', 'user_' . $shop->ID );
    $shop_img  = get_field( 'shop_img', 'user_' . $shop->ID );

    $post_id = wp_insert_post(
      array(
        'post_status' => 'publish',
        'post_title'  => $shop_name,
        'post_author' => $shop->ID,
        'post_name'   => $shop->user_nicename,
        'post_type'   => 'shop'
      )
      , $wp_error );
    update_post_meta($post_id,'eyecatch',$shop_img["id"]);
  }//end foreach
}
//add_action('admin_head','create_post_for_shopuser');

functions.php

//店舗ユーザーが変更した際にカスタム投稿タイプSHOPも変更
/*============================================== */
function my_profile_update( $user_id, $old_user_data ) {
    $user = get_user_by('id', $user_id);
    if(!in_array('editor',$user->roles)){return ;}//店舗ユーザー以外
    $shop_name = get_field( 'shop_name', 'user_' . $user_id );
    $shop_img  = get_field( 'shop_img', 'user_' . $user_id );

    $myposts = get_posts(
      array(
        'posts_per_page'   => -1,
        'post_type'        => 'shop',
        'author'           => $user_id,
      )
    );
    foreach ($myposts as $post) {
      wp_update_post(
        array(
          'ID'          => $post->ID,
          'post_title'  => $shop_name,
          'post_name'   => $shop->user_nicename,
          'post_type'   => 'shop'
        )
        , $wp_error );
      update_post_meta($post->ID,'eyecatch',$shop_img["id"]);
    }
}
add_action( 'profile_update', 'my_profile_update');
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0