Search code examples
phparrayswordpressvariablesadvanced-custom-fields

Merge multiple ACF variables in one array


I'm using ACF relationship fields. I'm displaying multiple hand selected posts blocks. There is a last posts block where I want to exclude all the hand selected ones before.

How do I make an array of all ACF's to select them to exclude them from the loop?

This is my code so far (not working, it works if I only use one variable)

<?php   
$excluir = get_field('bloque_6_posts');
$excluir2 = get_field('bloque_2_posts');
$excluir3 = get_field('post_destacado');
$excluir4 = get_field('posts_destacados');
$excluir5 = get_field('bloque_4_posts');
$excluirtodo = array (
  $excluir,
  $excluir2,
  $excluir3,
  $excluir4,
  $excluir5
);
$paged = (get_query_var('page')) ? get_query_var('page') : 1;
$args = array(
  'posts_per_page' => 9,
  'paged'          => $paged,
  'post__not_in' => $excluirtodo
);

$the_query = new WP_Query( $args ); 
?>

EDIT [SOLVED]: as @disinfor pointed on the comments the solution was array_merge instead of array


Solution

  • Adding my answer from the comments to help future visitors

    You are currently passing an array of arrays to the post__not_in. You need to use array_merge to combine the arrays into a single array.

    <?php   
    $excluir = get_field('bloque_6_posts');
    $excluir2 = get_field('bloque_2_posts');
    $excluir3 = get_field('post_destacado');
    $excluir4 = get_field('posts_destacados');
    $excluir5 = get_field('bloque_4_posts');
    
    // NEW CODE HERE
    $excluirtodo = array_merge(
      $excluir,
      $excluir2,
      $excluir3,
      $excluir4,
      $excluir5
    );
    // END ARRAY_MERGE
    $paged = (get_query_var('page')) ? get_query_var('page') : 1;
    $args = array(
      'posts_per_page' => 9,
      'paged'          => $paged,
      'post__not_in' => $excluirtodo
    );
    
    $the_query = new WP_Query( $args ); 
    ?>