雛箱

徒然 メモ 259

もういっそ縫い撮り関係の写真もこうやって一覧にしたら俺が楽しいんじゃない?と思ってカテゴリ増やして部屋も増やした んですが、ここら辺は別に更新履歴に載せなくて良いなーと思ったので、ようやくなんとか出来た先日のPHPを早速改変する必要が出て来てしまった訳です。お前はいつもそうだ。
途中、無が出力されてRSS通知が真っ白になったり、除外は出来たものの何故か今まで入れられてた画像更新の履歴が他URLに負けて出て来なくなったりもしましたが、何とか形になりました。多分。
後から思い付きで色々やるからそうなる。
あとついでだったので未分類も更新に出ないようにしました。まあ基本未分類になってるのはカテゴリ付け忘れミスなんですけれども。
<?php
header('Content-Type: application/rss+xml; charset=UTF-8');

// XML ヘッダ
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<rss version="2.0"><channel>';
echo '<title>Media Gallery Feed</title>';
echo '<link>' . home_url('/') . '</link>';
echo '<description>Media Gallery RSS</description>';

// 親カテゴリマップ
$parent_map = [
    'processed' => '加工写真',
    'knyacki'   => 'ニャッキ',
    'rtr'       => 'ドット絵化',
    'jpeg'      => 'Jpeg圧縮',
];

// 除外条件
$exclude_parent_slug = 'nui';           // 親に nui がいたら除外
$exclude_term_slug   = 'uncategorized'; // 未分類を除外

// RSS表示用カテゴリ判定
function get_rss_category_info($post_id, $parent_map, $exclude_parent_slug, $exclude_term_slug) {
    $terms = wp_get_post_terms($post_id, 'category');
    if (empty($terms) || is_wp_error($terms)) return false;

    // 除外判定
    foreach ($terms as $term) {
        if ($term->slug === $exclude_term_slug) return false;

        $ancestors = get_ancestors($term->term_id, 'category');
        foreach ($ancestors as $aid) {
            $ancestor = get_term($aid, 'category');
            if ($ancestor && $ancestor->slug === $exclude_parent_slug) {
                return false;
            }
        }
    }

    // RSS表示用カテゴリ決定
    foreach ($terms as $term) {
        $ancestors = get_ancestors($term->term_id, 'category');

        if ($ancestors) {
            $top = get_term(end($ancestors), 'category');

            // photo → 孫カテゴリ
            if ($top && $top->slug === 'photo' && count($ancestors) >= 2) {
                $child = get_term($ancestors[count($ancestors) - 2], 'category');
                return [
                    'key'  => 'photo/' . $child->slug . '/' . $term->slug,
                    'name' => $term->name,
                    'link' => home_url("/photo/{$child->slug}/{$term->slug}/")
                ];
            }

            // その他 → 親カテゴリ
            if ($top && isset($parent_map[$top->slug])) {
                return [
                    'key'  => $top->slug,
                    'name' => $parent_map[$top->slug],
                    'link' => home_url("/{$top->slug}/")
                ];
            }
        } else {
            if (isset($parent_map[$term->slug])) {
                return [
                    'key'  => $term->slug,
                    'name' => $parent_map[$term->slug],
                    'link' => home_url("/{$term->slug}/")
                ];
            }
        }
    }

    return false;
}

// 画像添付投稿取得
$attachments = get_posts([
    'post_type'      => 'attachment',
    'post_mime_type' => 'image',
    'numberposts'    => 50,
    'orderby'        => 'date',
    'order'          => 'DESC',
]);

if ($attachments) {

    $grouped = [];

    // 60分 + カテゴリ単位でまとめ
    foreach ($attachments as $post) {
        $id   = $post->ID;
        $time = strtotime($post->post_date);

        $cat = get_rss_category_info(
            $id,
            $parent_map,
            $exclude_parent_slug,
            $exclude_term_slug
        );
        if (!$cat) continue;

        $found = false;
        foreach ($grouped as &$g) {
            if (
                $g['key'] === $cat['key'] &&
                abs($g['time'] - $time) <= 3600
            ) {
                $g['ids'][] = $id;
                $found = true;
                break;
            }
        }

        if (!$found) {
            $grouped[] = [
                'time' => $time,
                'ids'  => [$id],
                'key'  => $cat['key'],
                'name' => $cat['name'],
                'link' => $cat['link'],
            ];
        }
    }

    // <item> 出力
    foreach ($grouped as $g) {
        $rep_id = $g['ids'][0];
        $date   = get_the_date('Y.m.d', $rep_id);

        $extra_count = max(0, count($g['ids']) - 1);
        $extra_text  = $extra_count ? "(他{$extra_count}枚)" : '';

        echo '<item>';
        echo '<title><![CDATA[' . $date . ' - ' . $g['name'] . ' - #' . $rep_id . $extra_text . ']]></title>';
        echo '<link>' . esc_url($g['link']) . '</link>';
        echo '<guid>media-gallery?id=' . $rep_id . '</guid>';
        echo '<pubDate>' . get_the_date('r', $rep_id) . '</pubDate>';
        echo '<source url="' . esc_url($g['link']) . '">' . $g['name'] . '</source>';
        echo '</item>';
    }
}

echo '</channel></rss>';
?>
畳む

結果的には'numberposts' =>の値を変えた(RSSに載せない写真を大量にアップしたので通知させたい写真が後ろに流れ感知しなくなったっぽい)のと、// 除外条件
$exclude_parent_slug = 'nui';           // 親に nui がいたら除外
$exclude_term_slug   = 'uncategorized'; // 未分類を除外
を追加したくらいなんですけれども、入れる位置とかで色々挙動が意図しないことになったりしたのでPHPって難しいですね…

#WordPress

  徒然 メモ  編集