0

The following php will loop through each page and then output ALL of the ACF custom fields sequentially. What I need help formatting is a conditional statement that places all $fields, except $field_name containing 'title', in their own container.

$pages = get_pages( array('sort_column' => 'menu_order')); 
foreach ($pages as $page_data) {
    $fields = get_fields($page_data);
    if( $fields )
    {

      foreach( $fields as $field_name => $value )
      {

       $field = get_field_object($field_name, false, array('load_value' => false));

       // if(strpos($field_name,"title") !== false ){
       // /*this field has name containing title*/
       // }

       echo '<div class='.$field_name.'>';
       echo $value;
       echo '</div>';

      }
    }

}

So final HTML should look like:

<div class="the_title">TITLE</div>
  <div class="container">
     <div class="1">1</div>
     <div class="2">2</div>
     <div class="3">3</div>
  </div>

Thanks for your advice.

  • What is the name of the exact name of the key storing your title? Or are they programmaticaly generated into something like title_0097 or similar? – user10106 Jan 17 '14 at 21:08
  • @MichaelJames I can explicitly define them. i.e. the could all be "the_title". – sweeds Jan 20 '14 at 17:23
  • @sweeds with strpos($field_name, 'title') !== FALSE you're checking if the string "title" exists anywhere within $field_name. with strpos($field_name, 'title') === 0 you're checking if "title" is positioned at the very beginning of $field_name. If you're checking just strpos($field_name, 'title') you can't know if it's one or the other. – Mihai Stancu Jan 21 '14 at 7:27
0

If it can be explicetly defined as the_title, then this should work for you:

$pages = get_pages(array ('sort_column' => 'menu_order')); 

foreach ($pages as $page_data) { 
    $fields = get_fields($page_data); 
    if( $fields ) {
        echo '<div class="the_title">' .$fields['the_title'] . '</div>';
        echo '<div class="container">';
        foreach( $fields as $field_name => $value ) { 
            $field = get_field_object($field_name, false, array('load_value' => false)); 

            if($field_name != 'the_title' ){  /*this field does not have key of 'the_title'*/
                echo '<div class='.$field_name.'>';
                    echo $value; 
                echo '</div>'; 
              }

         }
        echo '</div>'; 

    } 
}

Apologies if there are any erroneous gaps. My phone likes to drop in spaces when I'm writing code for some reasons.

any questions, ask away.

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.