testing-env-setup.php

Award Custom Post Type

This WordPress file contains code to create a custom post type named 'awards' with additional meta fields to store award details such as year, category, and type. It also includes functions to add and save these meta fields, as well as a function to generate test data.

<?php // Register a new post type called "awards" function codewp_create_post_type() { register_post_type( 'awards', array( 'labels' => array( 'name' => __( 'Awards' ), 'singular_name' => __( 'Award' ) ), 'public' => true, 'has_archive' => true, ) ); } add_action( 'init', 'codewp_create_post_type' ); // Add meta fields for award year, award sort category, and award type function codewp_add_award_meta_boxes() { add_meta_box( 'codewp_award_meta_box', // id of the meta box 'Award Details', // title 'codewp_display_award_meta_box', // callback function 'awards', // post type 'normal', // context 'high' // priority ); } add_action('add_meta_boxes', 'codewp_add_award_meta_boxes'); function codewp_display_award_meta_box($post) { $year = get_post_meta($post->ID, 'awd_year', true); $sort_cat = get_post_meta($post->ID, 'awd_sort_cat', true); $type = get_post_meta($post->ID, 'awd_type', true); // Display fields echo 'Year: <input type="text" name="awd_year" value="' . $year . '"><br>'; echo 'Category: <input type="text" name="awd_sort_cat" value="' . $sort_cat . '"><br>'; echo 'Type: <input type="text" name="awd_type" value="' . $type . '"><br>'; } // Save meta box fields function codewp_save_award_meta_box($post_id) { if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } if (isset($_POST['awd_year'])) { update_post_meta($post_id, 'awd_year', $_POST['awd_year']); } if (isset($_POST['awd_sort_cat'])) { update_post_meta($post_id, 'awd_sort_cat', $_POST['awd_sort_cat']); } if (isset($_POST['awd_type'])) { update_post_meta($post_id, 'awd_type', $_POST['awd_type']); } } add_action('save_post', 'codewp_save_award_meta_box'); // Function to create test data function codewp_create_test_data() { $test_data = array( array('awd_year' => '2020', 'awd_sort_cat' => 'Best Actor', 'awd_type' => 'Nominee'), array('awd_year' => '2020', 'awd_sort_cat' => 'Best Actress', 'awd_type' => 'Winner'), // Add more test data here... ); foreach ($test_data as $data) { $post_id = wp_insert_post(array( 'post_type' => 'awards', 'post_title' => 'Test Award', 'post_status' => 'publish', )); update_post_meta($post_id, 'awd_year', $data['awd_year']); update_post_meta($post_id, 'awd_sort_cat', $data['awd_sort_cat']); update_post_meta($post_id, 'awd_type', $data['awd_type']); } } //Run manually //codewp_create_test_data(); ?>

Frequently Asked Questions

The custom post type feature allows users to create their own post types with specific characteristics not covered by default post types like posts or pages.