The way to do this is to add a custom Meta Box with add_meta_box()
and within the box list your CPT posts using get_posts()
. And the information will be recorded as a Custom Field using update_post_meta()
. Note that if Custom Field starts with a underscore (_NomeDoField
), he is invisible in the standard custom Fields box.
In this example, the Meta Box is added to the regular Posts and the listing is of CPT Portfolio entries. Adjust as needed in the indicated locations.
<?php
/**
* Plugin Name: (SOPT) Listagem de CPT em Meta Box
* Plugin URI: /a/16674/201
* Author: brasofilo
*/
add_action( 'add_meta_boxes', 'add_box_sopt_16606' );
add_action( 'save_post', 'save_postdata_sopt_16606', 10, 2 );
function add_box_sopt_16606()
{
add_meta_box(
'sectionid_sopt_16606',
__( 'CPT Associado' ),
'cpt_box_sopt_16606',
'post', # <--- Ajuste CPT
'side'
);
}
function cpt_box_sopt_16606()
{
global $post;
// Puxar todos as entradas do CPT
$args = array(
'numberposts' => -1,
'post_type' => 'portfolio', # <--- Ajuste CPT
'post_status' => 'publish,future'
);
$get_posts = get_posts( $args );
// Valor gravado ou default
$saved = get_post_meta( $post->ID, '_cpt_associado', true );
if( !$saved )
$saved = array();
// Segurança
wp_nonce_field( plugin_basename( __FILE__ ), 'noncename_sopt_16606' );
if( $get_posts )
{
foreach ( $get_posts as $cpt_post )
{
printf(
'<input type="checkbox" name="_cpt_associado[%1$s]" value="%1$s" id="_cpt_associado[%1$s]" %3$s />'.
'<label for="_cpt_associado[%1$s]"> %2$s ' .
'</label><br>',
esc_attr( $cpt_post->ID ),
esc_html( $cpt_post->post_title ),
checked( in_array( $cpt_post->ID, $saved ), true, false )
);
}
}
else
echo '<strong>O CPT não tem entradas</strong>';
}
function save_postdata_sopt_16606( $post_id, $post_object )
{
// Não é nosso tipo, sair fora
if ( 'post' !== $post_object->post_type ) # <--- Ajuste CPT
return;
// Fazendo auto save?
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// Segurança
if (
!isset( $_POST['noncename_sopt_16606'] )
|| !wp_verify_nonce( $_POST['noncename_sopt_16606'], plugin_basename( __FILE__ ) )
)
return;
// Gravar ou deletar
if ( isset( $_POST['_cpt_associado'] ) )
update_post_meta( $post_id, '_cpt_associado', $_POST['_cpt_associado'] );
else
delete_post_meta( $post_id, '_cpt_associado' );
}
Upshot
Code adapted from List of Posts in a Custom Field