A
A
Alex-Broudy2020-04-16 19:03:02
WordPress
Alex-Broudy, 2020-04-16 19:03:02

How to hide a DIV containing a post loop if a custom field in the loop is empty?

All the best!

Tell me what I'm doing wrong?

There is a DIV block with the "books" class, which contains a loop for displaying posts.

I want to check that if the value of an arbitrary field ('value' => ') in the loop is not empty and contains the word 'Glossy', then the block with the class "books" is shown, and if it is not filled or filled, but does not contain the word ' Glossy', then do not show.

I'm not strong in WP, so I asked for help ..

The code is below:

<? 
$book_id = get_field('book_id'); // по $book_id определяем ID поста из которого нужно вытянуть данные
$vid_oblojki = get_field('вид_обложки',$book_id);
?>

<? if (!empty($vid_oblojki['Глянцевая'])) : ?>
<div class="books">
  <?php 
  $posts = get_posts( array(
    'numberposts' => -1,
    'orderby'     => 'date',
    'order'       => 'DESC',
    'meta_query' => array(
      'relation' => 'AND', 
      array(
        'key'     => 'название_книги',
        'value'   => $book_name,
      ),
      array(
        'key'     => 'вид_обложки',
        'value'   => 'Глянцевая',
        'compare' => '=',
      ),
    ),
    'post_type'   => 'books',
  ) );
  foreach( $posts as $post ){
    setup_postdata($post);
  ?>
  <a href="<?php echo $book_link; ?>"><?php the_field('название_книги'); ?></a>
  <?php 
    }
    wp_reset_postdata();
  ?>
</div>
<?php else : ?>
  <!-- Ничего не показываем -->
<?php endif ?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WP Panda, 2020-04-16
@Alex-Broudy

You have a terrible mess
1, NEVER CALL ANY FIELDS IN CYRRILIC !!!!! NEVER.
2, it's not clear what you have stored in the 'cover_type' field , I still think it's a string, then the condition will look like this

if(!empty($vid_oblojki) && mb_substr($vid_oblojki,'глянцевая')) :
// код
        endif;

if all the same there is an array, then so
if ( ! empty( $vid_oblojki ) && mb_substr( implode( '', $vid_oblojki ), 'Глянцевая' ) ) :
  endif;

3. You don't properly organize this field.
Types of covers, as I understand it, a limited and predefined number, then you need to make this field a select with types of covers, and numerical values
<select name="cover_type" id="cover_type">
    <options value="">Выберите вид обложки</options>
    <options value="1">Мягкая</options>
    <options value="2">Глянцевая</options>
</select>

Then the check will look like this
if(!empty($vid_oblojki) && 2 === (int)$vid_oblojki) :
// код
        endif;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question