WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Store pages in array if "condition" (2 posts)

  1. anouskadg
    Member
    Posted 1 year ago #

    Hello everyone,

    I'm converting a static HTML website to a WordPress theme and things were going pretty well until now..
    I have already searched the forum and Google but I can't find the answer to my problem.

    I have 5 categories of pages. When adding a new page, you can define the category with the help of the 'Advanced Custom Fields' plugin.
    I can get the content of those custom fields using
    <?php the_field('categorie'); ?>
    or
    <?php get_field('categorie'); ?>
    (depending on the use of it).

    The original website has a list at the bottom of the page showing all the pages sorted by category. I would like to make this dynamic so that you don't have to add the page manually when you add a new page to your site.

    I would like to make a separate array for each category. In other words: the first array contains all pages with category 1, the second array contains all pages with category 2 etc.
    This might not be the easiest way, but it will help me with some other functions I need to add to the website.

    However, I have no clue on how to store the pages in an array based on category. And I also have no clue on how to show a list with the names of the pages in that category.

    I guess it should be something like this:

    if (get_field('categorie') == 'condition1') {
    add page to array1
    }
    else if (get_field('categorie') == 'condition2') {
    add page to array2
    }
    etc.

    But like I said, I have no clue on how to get it working.

    I am no PHP expert so I hope someone can help me.
    Much thanks in advance

  2. vtxyzzy
    Member
    Posted 1 year ago #

    Here is some sample code that may help. I do not have ACF installed, so I used in_category() to check the category.

    $args = array(
       'posts_per_page' => -1,
       'ignore_sticky_posts' => 1,
       'category__in' => array(32, 126, 7),  // The category ids
    );
    query_posts( $args );
    if (have_posts()) {
       while (have_posts()) {
          the_post();
          $link = '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
          // echo "$link<br />";  // For testing
          if( in_category(32) ) {
             $array1[] = $link;
          } elseif ( in_category(126) ) {
             $array2[] = $link;
          } elseif ( in_category(7) ) {
             $array3[] = $link;
          }
       }
    }
    echo "<br />CATEGORY 32<br />";
    foreach ( $array1 as $link ) {
       echo "$link<br />";
    }
    echo "<br />CATEGORY 126<br />";
    foreach ( $array2 as $link ) {
       echo "$link<br />";
    }
    echo "<br />CATEGORY 7<br />";
    foreach ( $array3 as $link ) {
       echo "$link<br />";
    }

Topic Closed

This topic has been closed to new replies.

About this Topic