こんにちは、今回も備忘録的に載せていきます。
カテゴリーが増えてくると、色々なカテゴリにまたがる投稿が出てくると思います。
そこで、何かと必要になってっくるのがメインカテゴリをどれにするかということ。
メインコード
WordPressデフォルトだと、確か一番上のカテゴリが優先されたような。。すみません、ちょっと曖昧です。
そこで、ビシッとこれをメインでと設定したいときには下記コードをfuntions.phpへ追加しましょう。
/**
* Add Meta Box for Main Term Selection (Custom Taxonomy)
*/
function add_main_term_meta_box() {
add_meta_box(
'main_term_meta_box', // ID
'メインカテゴリ', // Title
'render_main_term_meta_box', // Callback
'shop', // Post type (change if needed)
'side', // Context
'default' // Priority
);
}
add_action('add_meta_boxes', 'add_main_term_meta_box');
/**
* Render the Main Term Meta Box with Searchable Dropdown
*/
function render_main_term_meta_box($post) {
$taxonomy = 'shop-category'; // Change to your custom taxonomy
// Get all terms from the taxonomy
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => false,
'orderby' => 'name',
'order' => 'ASC',
]);
// Get saved main term
$selected_term = get_post_meta($post->ID, 'main_term_' . $taxonomy, true);
// Security nonce
wp_nonce_field('save_main_term_' . $taxonomy, 'main_term_nonce_' . $taxonomy);
echo '<label for="main_term_select">選択もしくは検索</label>';
echo '<select name="main_term" id="main_term_select" style="width:100%;">';
echo '<option value="">-- None --</option>';
foreach ($terms as $term) {
$selected = ($selected_term == $term->term_id) ? 'selected' : '';
echo '<option value="' . esc_attr($term->term_id) . '" ' . $selected . '>' . esc_html($term->name) . '</option>';
}
echo '</select>';
}
/**
* Save Main Term Meta Box Data
*/
function save_main_term_meta_box($post_id) {
$taxonomy = 'shop-category'; // Change to your custom taxonomy
// Verify nonce
if (!isset($_POST['main_term_nonce_' . $taxonomy]) || !wp_verify_nonce($_POST['main_term_nonce_' . $taxonomy], 'save_main_term_' . $taxonomy)) {
return;
}
// Check for autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check user permissions
if (!current_user_can('edit_post', $post_id)) {
return;
}
// Validate and sanitize input
if (isset($_POST['main_term'])) {
$main_term = sanitize_text_field($_POST['main_term']);
if (!empty($main_term) && term_exists((int)$main_term, $taxonomy)) {
update_post_meta($post_id, 'main_term_' . $taxonomy, $main_term);
} else {
delete_post_meta($post_id, 'main_term_' . $taxonomy);
}
}
}
add_action('save_post', 'save_main_term_meta_box');
表示側コード
表示側では下記のようなコードが使えます。メインカテゴリが設定されていればその名前を、なければNULLを返します。この辺りは自由にカスタマイズしてください。
//
//
function display_main_term($post_id = null, $taxonomy = 'taxonomy') {
$post_id = $post_id ? $post_id : get_the_ID();
// Get saved main term
$main_term_id = get_post_meta($post_id, 'main_term_' . $taxonomy, true);
if ($main_term_id) {
$term = get_term($main_term_id, $taxonomy);
if ($term && !is_wp_error($term)) {
return esc_html($term->name);
}
}
return null;
}