1

I have created custom fields for posts by using the add_meta_box action. I want to create my own WP Query based on my custom field, to make sure I will only load a post collection with the correct data. If I add a new field, the post doesn't automatically have a value for my custom field. So I am not able to load the proper collection without manually saving all the posts. I've got over 1200 posts, so it's going to be really difficult to change them all and set the value in the database.

The field which I created should be automatically set on "true". If the field is true, I will show the posts on a specific page. I currently want all posts I have to be shown on that page, so all 1200 posts should be loaded. In the future the posts will be sorted out and some posts should not be shown on the homepage.

I created the field using the add_meta_boxes action. Showing the field, editing the field and saving the field works properly.

/**
 * Add Meta Box to post
 */
if(!function_exists('theme_settings_add_post_meta_box')) {
    function theme_settings_add_post_meta_box()
    {
        $screens = array('post');

        foreach ($screens as $screen) {
            add_meta_box(
                'theme_settings_section_slider',
                __('Homepage Slider', 'slidedata'),
                'theme_settings_section_slider_callback',
                $screen,
                'normal',
                'high'
            );
        }
    }
}

I have created the form elements in the function "theme_settings_section_slider_callback". I have copied the custom field which I want to filter by:

$showPost = 'theme_settings_post_show';
<?php /** Show post on frontend */ ?>
<label for="<?php echo $showPost ?>"><?php _e('Show post on homepage') ?></label>
<br />
<select style="margin-bottom: 20px" name="<?php echo $showPost ?>" id="<?php echo $showPost ?>">
    <option value="false" <?php echo get_post_meta($object->ID, $showPost, true)  == 'false' ? '' : 'selected' ?>>No</option>
    <option value="true" <?php echo get_post_meta($object->ID, $showPost, true) != 'false' ? 'selected' : '' ?>>Yes</option>
</select>

Save function (which also works fine)

if(!function_exists('theme_settings_save_post_meta_box')) {
    function theme_settings_save_post_meta_box($post_id, $post) {
        // Add a check if this account has permission to save, maybe?
        .....
        $data['show_post']      = 'theme_settings_post_show';

        foreach($data as $item) {
            if(isset($_POST[$item])) {
                $value = $_POST[$item];
                update_post_meta($post_id, $item, $value);
            }
        }
    }
}

The field logic works just fine. This is the query I use to show the posts based on the field "theme_settings_post_show":

//Get all posts which have to be shown on the homepage
if(!function_exists('getPosts')) {
    function getPosts() {
        //$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

        //Query arguments
        $queryArguments = array(
            'posts_per_page' => -1,
            'post_type'     => 'post',
            'meta_key'      => 'theme_settings_post_show',
            'meta_value'    => 'true'
        );

        $postsQuery = new WP_Query($queryArguments);

        if($postsQuery->have_posts()) {
            return $postsQuery;
        }

        return false;
    }
}

As you can expect, the field "theme_settings_post_show" is not set for any post yet, so I'm not retrieving any post with my function "getPost". I have also tried filtering by meta_value null, but that doesn't work.

So, my question is: How can I create a field which automatically has a default value for all posts? Or am I forced to create some sort of script which loops through all posts and set the data automatically? Or am I using a wrong method to add the fields to the post?

2

Try meta_query to get posts having theme_settings_post_show == true (for new posts) and theme_settings_post_show not set at all (for old posts):

<?php
$queryArguments = array(
    'posts_per_page' => -1,
    'post_type'     => 'post',
    'meta_query' => array(
       'relation' => 'OR', // value is not set or true
        array(
         'key' => 'theme_settings_post_show',
         'value' => '', // can be any value, since it does not exists
         'compare' => 'NOT EXISTS',
        ),
        array(
         'key' => 'theme_settings_post_show',
         'value' => true,
         'compare' => '=',
        ),
    ),
);
  • Ah, thanks! I was looking for something like that. I will try this in a couple of hours. I will write a conclusion when I have tested the code. – Stefan R Jan 17 '18 at 9:46
0

Advanced Custom Fields plugin also has a true/false type of field, which you can add to specific posts, post types pages and so on, and you can also define the default value.

But this would only work on newly added posts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.