最近用 WordPress 做網站有一個需求是要檢查文章裡如果有特定的標籤,會把他抓出來後去轉換成特定的文章陣列,以下為實作的方法。

首先先設計一個 function,用來比對標籤並轉換成新的陣列。

function compare_tags_with_custom_map($posttags, $custom_map) {
    $matched_post_ids = array();

    if ($posttags) {
        foreach ($posttags as $tag) {
            // 檢查標籤名稱是否在自定義映射中
            if (isset($custom_map[$tag->name])) {
                $matched_post_ids[] = $custom_map[$tag->name];
            }
        }
    }

    return $matched_post_ids;
}

 

取得文章的標籤以及自己設定的對應文章關聯式陣列。

// 使用 get_the_tags() 獲取文章的標籤陣列
$posttags = get_the_tags();

// 自定義的關聯式陣列
$custom_tag_to_post_map = array(
    '關鍵字1' => 123, // 文章 ID 1
    '關鍵字2' => 456, // 文章 ID 2
    // 其他關聯
);

 

將兩個陣列比對後產出新的陣列:

// 將文章的標籤陣列與自定義映射進行比對
$matched_post_ids = compare_tags_with_custom_map($posttags, $custom_tag_to_post_map);

if (!empty($matched_post_ids)) {
    echo '符合條件的文章 ID:' . implode(', ', $matched_post_ids);
} else {
    echo '未找到符合條件的文章。';
}

這個 compare_tags_with_custom_map 函數接受兩個參數:

  1. $posttags:由 get_the_tags() 函數獲取的文章標籤陣列。
  2. $custom_map:自定義的關聯式陣列,將標籤名稱映射到文章 ID。

函數遍歷 $posttags 陣列,對每個標籤檢查是否在自定義映射中,如果符合條件,則將相應的文章 ID 添加到 $matched_post_ids 陣列中。

最後,如果存在符合條件的文章 ID,則輸出這些文章 ID,否則輸出未找到符合條件的文章。

這樣就可以比對自定義的關聯式陣列和文章的標籤陣列,並產生包含符合條件的文章 ID 的新陣列。