12
12

More than 5 years have passed since last update.

[WordPress]マルチサイトで別ブログの記事が属するカスタムタクソノミーを取得

Posted at

switch_to_blogしてget_taxonomiesをしても取得できない。
調べたら、

[WordPress]switch_to_blog()を使うとget_terms()が動かないので、直接DBからデータを取得する

にばっちりの方法がかかれていた。ありがたい。
でもカスタムタクソノミーのslugが被るとうまくいかなかったので以下のようにした。

function.php
function get_taxonomies_by_blog_post($taxonomy, $blog_id, $post_id) {
    // ブログを切り替える
    switch_to_blog($blog_id);
    global $wpdb;
    // クエリ作成
    $query = "
    SELECT *
    FROM $wpdb->term_relationships
    LEFT JOIN $wpdb->term_taxonomy
        ON $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id
    LEFT JOIN $wpdb->terms
        ON $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id
    WHERE $wpdb->term_relationships.object_id = %d
        AND $wpdb->term_taxonomy.taxonomy = %s
    ";
    // プレースホルダ
    $args = array($post_id, $taxonomy);
    // データを取得
    $taxonomies = $wpdb->get_results( $wpdb->prepare( $query, $args ) );
    // ブログを戻す
    restore_current_blog();
    return $taxonomies;
    }
引数
$taxonomy 取得するカスタムタクソノミー名
$blog_id 取得するブログID
$post_id 取得する投稿ID

テンプレートではこんな感じで使う

<?php
switch_to_blog(2);
$args = array( 'post_type' => array('hogehgoe') );
$arr = get_posts( $args );
foreach($arr as $v ){ ?>
    <?php $cat = get_taxonomies_by_blog_post('hogehoge_taxonomy', 2, $v->ID); ?>
    <a href="<?php echo get_permalink($v->ID); ?>">
        <?php echo $cat[0]->name ?> : <?php echo esc_html($v->post_title); ?>
    </a>
<?php }
restore_current_blog(); ?>

カテゴリーをとってきてるのはここ

$cat = get_taxonomies_by_blog_post('hogehoge_taxonomy', 2, $v->ID);

ちなみに$catにはカテゴリー情報のオブジェクトが配列で入ってる。

var_dump($cat);

array(1) {
  [0]=>
  object(stdClass)#2806 (11) {
    ["object_id"]=>
    string(3) "111"
    ["term_taxonomy_id"]=>
    string(1) "1"
    ["term_order"]=>
    string(1) "2"
    ["term_id"]=>
    string(1) "4"
    ["taxonomy"]=>
    string(16) "hogehgoe_taxonomy"
    ["description"]=>
    string(0) ""
    ["parent"]=>
    string(1) "0"
    ["count"]=>
    string(2) "2"
    ["name"]=>
    string(12) "ほげほげ"
    ["slug"]=>
    string(7) "hogehoge"
    ["term_group"]=>
    string(1) "0"
  }
12
12
2

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
12
12