0

I have a skill development project I am working on here: https://blog.unicornpoint.net/wp/safe-foods-meal-generator-diet-assistant/ . This is a custom template page. I am using Custom Posts UI for custom post type meals and ACF for some custom fields. Over time, some of the meals stop displaying on the page. I have meals listed at the bottom depending on the size of the meal and meal groups that are displayed with jquery, ajax and php when you click on the button. BOTH methods stop displaying certain meal post types after a while. It is not always the same type or size. Is it some kind of caching thing? I am still learning all this and I could use some help.

Jquery script

    <div class="mx-auto meal-icons-container">
        <div class="row p-2 mx-auto">
            <div class="col-6 col-md-3">
                <img src="https://blog.unicornpoint.net/wp/wp-content/uploads/2020/02/panic.png" id="emergency-icon" width="75" height="auto" alt="Emergency Meals" class="meal-icon"><span class="meal-icon-caption"> Emergency</span>
            </div>
            <script>
                jQuery(document).ready(function($){
                    $('#emergency-icon').click(function(){
                        $.ajax({
                            method: 'GET',
                url: ajaxurl, // we send all WP ajax requests to this file, it will load all WP's files, plugins. It's WP Ajax approach.
                data: {
                  action: 'load_emergency_meals' // you can name it whatever just use the same in PHP binding ajax action.
              }
          }).done(function(data){
            $("#meal-results").html(data);
          });
      });
                });
            </script>

Function in functions.php

// load emergency meals button
function load_emergency_meals() {
 ?>
    <h2>
        Emergency Binge Control Meals
    </h2>
<div class="justify-content-center d-inline-flex flex-wrap text-center p-2">
    <?php
    $args = array('post_type' => 'meal');
    $meals = new WP_Query($args);

    if($meals->have_posts()) : while($meals->have_posts()) : $meals->the_post();
        $meal_type = get_field('meal_type');
        if ( $meal_type && in_array('emergency', $meal_type)){?>
            <div class="text-center p-2 meal-size-posts">
                <h4><?php the_field('meal_name'); ?></h4>
                <img src="<?php echo get_field('meal_icon'); ?>" class="meal-icon">
                <p class="meal-description"><?php the_field('meal_description'); ?></p>
                <h4><?php the_field('meal_calories'); ?> calories</h4>
            </div>
        <?php } ?>
    <?php endwhile; endif; ?>
</div>
<?php
    die();
}

Actions in function.php

 // this is where we bind our function to `load_meals` action name.
 // the one with `_nopriv` prefix in wp action name is for not logged in users, and without it for logged in users.
add_action('wp_ajax_load_emergency_meals', 'load_emergency_meals');
add_action('wp_ajax_nopriv_load_emergency_meals', 'load_emergency_meals');

Custom Post Type Settings https://blog.unicornpoint.net/wp/wp-content/uploads/2020/03/meals-cpt-settings.jpg

Custom Fields Settings

if( function_exists('acf_add_local_field_group') ):

acf_add_local_field_group(array(
    'key' => 'group_5e590c435c453',
    'title' => 'Meal',
    'fields' => array(
        array(
            'key' => 'field_5e591fd27bd3f',
            'label' => 'Name',
            'name' => 'meal_name',
            'type' => 'text',
            'instructions' => 'What is this meal called?',
            'required' => 1,
            'conditional_logic' => 0,
            'wrapper' => array(
                'width' => '',
                'class' => '',
                'id' => '',
            ),
            'default_value' => '',
            'placeholder' => 'name the meal',
            'prepend' => '',
            'append' => '',
            'maxlength' => '',
        ),
        array(
            'key' => 'field_5e5920a99f373',
            'label' => 'Meal Icon',
            'name' => 'meal_icon',
            'type' => 'image',
            'instructions' => 'Choose an icon for this food.',
            'required' => 1,
            'conditional_logic' => 0,
            'wrapper' => array(
                'width' => '',
                'class' => '',
                'id' => '',
            ),
            'return_format' => 'url',
            'preview_size' => 'medium',
            'library' => 'all',
            'min_width' => '',
            'min_height' => '',
            'min_size' => '',
            'max_width' => '',
            'max_height' => '',
            'max_size' => '',
            'mime_types' => '',
        ),
        array(
            'key' => 'field_5e592164996b4',
            'label' => 'Meal Description',
            'name' => 'meal_description',
            'type' => 'textarea',
            'instructions' => 'Describe the meal.',
            'required' => 1,
            'conditional_logic' => 0,
            'wrapper' => array(
                'width' => '',
                'class' => '',
                'id' => '',
            ),
            'default_value' => '',
            'placeholder' => 'What foods are in this meal and what\'s the calorie breakdown?',
            'maxlength' => '',
            'rows' => '',
            'new_lines' => '',
        ),
        array(
            'key' => 'field_5e590c7a69cc7',
            'label' => 'Calories',
            'name' => 'meal_calories',
            'type' => 'number',
            'instructions' => 'Add how many calories this meal contains.',
            'required' => 1,
            'conditional_logic' => 0,
            'wrapper' => array(
                'width' => '',
                'class' => '',
                'id' => '',
            ),
            'default_value' => '',
            'placeholder' => 'add calories',
            'prepend' => '',
            'append' => '',
            'min' => '',
            'max' => '',
            'step' => '',
        ),
        array(
            'key' => 'field_5e6e03dd8dee2',
            'label' => 'Meal Type',
            'name' => 'meal_type',
            'type' => 'checkbox',
            'instructions' => '',
            'required' => 1,
            'conditional_logic' => 0,
            'wrapper' => array(
                'width' => '',
                'class' => '',
                'id' => '',
            ),
            'choices' => array(
                'emergency' => 'emergency',
                'basic' => 'basic',
                'alcoholic' => 'alcoholic',
                'asian' => 'asian',
                'mexican' => 'mexican',
                'comfort' => 'comfort',
                'cooling' => 'cooling',
                'sweet' => 'sweet',
            ),
            'allow_custom' => 0,
            'default_value' => array(
            ),
            'layout' => 'vertical',
            'toggle' => 0,
            'return_format' => 'value',
            'save_custom' => 0,
        ),
        array(
            'key' => 'field_5e6e04b63a353',
            'label' => 'Meal Size',
            'name' => 'meal_size',
            'type' => 'select',
            'instructions' => '',
            'required' => 1,
            'conditional_logic' => 0,
            'wrapper' => array(
                'width' => '',
                'class' => '',
                'id' => '',
            ),
            'choices' => array(
                'small' => 'small',
                'medium' => 'medium',
                'large' => 'large',
                'xl' => 'xl',
            ),
            'default_value' => array(
            ),
            'allow_null' => 0,
            'multiple' => 0,
            'ui' => 0,
            'return_format' => 'value',
            'ajax' => 0,
            'placeholder' => '',
        ),
    ),
    'location' => array(
        array(
            array(
                'param' => 'post_type',
                'operator' => '==',
                'value' => 'meal',
            ),
        ),
    ),
    'menu_order' => 0,
    'position' => 'normal',
    'style' => 'default',
    'label_placement' => 'top',
    'instruction_placement' => 'label',
    'hide_on_screen' => array(
        0 => 'the_content',
        1 => 'featured_image',
    ),
    'active' => true,
    'description' => '',
));

endif;

What could this problem be? Any help appreciated. Thanks.

1 Answer 1

0

So Why?

Because your WP_Query/query is querying the recent posts for your post type (for all meal types), so the results would likely not (always) contain those posts where the meal_type meta contains emergency as part of the value.

Yet, your code below is only displaying the post if it's of the specified meal type, which is emergency in your code:

$meal_type = get_field('meal_type');
if ( $meal_type && in_array('emergency', $meal_type))

Solution

Use meta query in your $args:

$args = array(
    'post_type'  => 'meal',
    'meta_query' => array(
        array(
            'key'     => 'meal_type',
            'value'   => '"emergency"',
            'compare' => 'LIKE',
        ),
    ),
);

A bit of explanation: In the above meta query, we're using the LIKE clause because the meta value is an array with a serialized string which may look like a:1:{i:0;s:9:"emergency";} in the database, so we're using an exact match — "<the type>". And it should work with your current ACF settings, but you'd need to adjust the value accordingly for other meal types. E.g. With the "basic" meal type, you'd use 'value' => '"basic"' (note the quotes/" are necessary).

A Better Practice

I would create a custom taxonomy named meal_type and assign it to the post type (meal). Or I might just use the default Category (category) taxonomy. But either way, I wouldn't need to use the above meta query, or that it's easier to query by the category/taxonomy and categorizing is what taxonomy is meant for. So you should consider that before you create more posts..

3
  • For now I am using the solution provided and it is working and has solved the problem. I will create a custom taxonomy for my next project. Thank you so much for your help.I am seeing those double quotes also. Mar 17, 2020 at 4:18
  • Alright then, just remember for grouping things together, using taxonomy is the proper approach - use meta only for dynamic things/strings like date, prices and custom captions/titles. And sorry, I forgot to mention in the answer that you'd no longer need to use the conditional - if ( $meal_type && in_array('emergency', $meal_type)) - just display all posts returned by WP_Query. Btw, your site's graphics are cute.. ;)
    – Sally CJ
    Mar 18, 2020 at 1:20
  • 1
    thank you, Sally. i did figure that out about the conditional statement was no longer needed. I have a database for my CD collection that I want to bring into Wordpress for myself. Maybe others can view it but, only I can edit it. The CD project I will use the taxonomy stuff. The site graphics came from Envato Elements. My work allows me to use these assets for skills development. I thought they were cute also. Mar 18, 2020 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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