Add a field to your form that allows selection of a machine
. You can use get_posts
to generate a select
element:
$args = [
'posts_per_page' => -1,
'post_type' => 'machine'
];
$machines = get_posts( $args );
if( ! empty( $machines ) ){
echo '<select name="_machine_id">';
foreach( $machines as $machine ){
echo '<option value="' . $machine->ID . '" >' . get_the_title( $machine ) . '</option>';
}
echo '</select>';
}
Save that value in post meta for the enquiry
post under the key _machine_id
.
To add a Machine column to the enquiry
post type list screen, use the manage_$post_type_posts_columns
filter:
function wpd_enquiry_posts_columns( $columns ) {
$columns['machine'] = 'Machine';
return $columns;
}
add_filter( 'manage_enquiry_posts_columns', 'wpd_enquiry_posts_columns' );
Next, use the manage_$post_type_posts_custom_column
action to output a value in that column for each post:
function wpd_enquiry_column( $column, $post_id ) {
if ( 'machine' === $column ) {
// get the machine ID saved in meta
$machine_id = get_post_meta( $post_id, '_machine_id', true );
if( $machine_id ){
// get the machine post
$machine = get_post( $machine_id );
if( is_object( $machine ) ){
echo get_the_title( $machine );
}
} else {
echo 'none';
}
}
}
add_action( 'manage_enquiry_posts_custom_column', 'wpd_enquiry_column', 10, 2 );
For the individual enquiry
post edit screens, you can add a meta box to display the machine. Here we add a meta box:
function wpd_machine_meta_box() {
add_meta_box( 'machine-id', 'Machine', 'wpd_display_machine_meta_box', 'enquiry' );
}
add_action( 'add_meta_boxes', 'wpd_machine_meta_box' );
And then the display function for the meta box:
function wpd_display_machine_meta_box( $post ) {
$machine_id = get_post_meta( $post->ID, '_machine_id', true );
if( $machine_id ){
$machine = get_post( $machine_id );
if( is_object( $machine ) ){
echo get_the_title( $machine );
}
} else {
echo 'none';
}
}
Here we have just a simple display of a static value, you can also generate a form field in your meta box, like the first function above, and hook post_save
to allow the admin to update the value.