get_posts custom field

This is a silly question, but I can’t find the proper way to ask it to google. so, sorry if this is a repetitive question.

I give a custom field with a checked that the user can check if he want this specific post to go the home page. So in my home page, I call for all the post who has the checked activated.

I am creating my custom field for the custom post type CV:

function add_custom_post_meta_box() {
add_meta_box(
‘custom_post_meta_box’, // $id
‘Campos Personalizados’, // $title
‘show_custom_post_meta_box’, // $callback
‘cv’, // $screen
‘normal’, // $context
‘high’ // $priority
);
}
add_action( ‘add_meta_boxes’, ‘add_custom_post_meta_box’ );

But inside this custom post meta box, I have multiple fields, like a label and a checkbox:

function show_custom_post_meta_box() {
global $post;
$meta = get_post_meta( $post->ID, ‘your_fields’, true ); ?>
<p>
<label for=”your_fields[text]”>Especialidad</label>
<br>
<input type=”text” name=”your_fields[text]” id=”your_fields[text]” class=”regular-text” value=”
<?php if (is_array($meta) && isset($meta[‘text’])){ echo $meta[‘text’];} ?>”>
</p>
<p>
<label for=”your_fields[checkbox]”>Mostrar en Home
<input type=”checkbox” name=”your_fields[checkbox]” value=”checkbox”
<?php
if (is_array($meta) && isset($meta[‘checkbox’])){
if ( $meta[‘checkbox’] === ‘checkbox’ ) echo ‘checked’;
}
?>>
</label>
</p>

Okey, the rest of the code save the custom field and works perfectly. My problem is when I try to call it:

$posts = get_posts(array(
‘posts_per_page’ => -1,
‘post_type’ => ‘cv’
// ‘meta_key’ => ‘your_fields[checkbox]’, //This is wrong!!
// ‘meta_value’ => ‘checkbox’
));

And when I try to call the post info:

<?php
foreach( $posts as $post ):
setup_postdata( $post );
?>

<h2><a href=”<?php the_permalink() ?>”><?php the_title(); ?></a></h2>
<p>
<?php
$meta = get_post_meta( $post->ID, ‘your_fields’, true );
if (isset($meta[‘checkbox’])){
echo $meta[‘checkbox’];
}
?>
</p>
<?php endforeach; ?>

So, my question is: How can make my query, to bring me just the custom post types, with a checked activated.

Read more here:: get_posts custom field

Leave a Reply

Your email address will not be published. Required fields are marked *