WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Variables with "_" not working in foreach() loop in a theme

[Resolved] Variables with "_" not working in foreach() loop in a theme

  • Within a theme I am trying to work around the exclude_tree bug, using the code of this page : http://www.technokinetics.com/workaround-for-exclude_tree-bug-in-wp_list_pages/

    I will simplify the code to get to my problem :

    <?php $parent_pages_to_exclude = array(8,233);
         foreach ($parent_page_to_exclude as $page_to_exclude) :
                echo "page_id: $page_to_exlude";
         endforeach;
    ?>

    This does not work at all, and does not show any error.

    When I am trying the same code naming the variables differently, I get the expected result :

    <?php $lols = array(8,233);
         foreach ($lols as $lol) :
             echo "lol $lol";
         endforeach;
    ?>

    What am I missing here? Are variable names expected to not contain underscores anymore?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Michael

    @alchymyth

    typo alert:
    wrong $parent_pages_to_exclude in first line

    corrected:

    <?php $parent_page_to_exclude = array(8,233);
         foreach ($parent_page_to_exclude as $page_to_exclude) :
                echo "page_id: $page_to_exlude";
         endforeach;
    ?>

    you must have the php warnings disabled, somehow;
    the code gave me an immediate

    Warning: Invalid argument supplied for foreach() in ..

    indeed there is a typo. It does not resolve my problem however.

    Ok, it had nothing to do with the variable names, neither with the foreach.
    So my simplified approach was totally useless as the problem was farther within the supplied workaround.

    Here is the modified code (for reference)

    <?php
                // wp_list_pages('exclude=2&exclude_tree=8,233&sort_column=menu_order&title_li=');
                // workaround for exclude_tree bug
                // http://www.technokinetics.com/workaround-for-exclude_tree-bug-in-wp_list_pages/
                $page_exclusions = '';
                $parent_pages_to_exclude = array(8,233);
                foreach ($parent_pages_to_exclude as $parent_page_to_exclude) :
                    $page_exclusions .= "$parent_page_to_exclude,";
                    $descendants = get_pages('child_of=' . $parent_page_to_exclude);
                    foreach($descendants as $descendant) {
                        $page_exclusions .= $descendant->ID .',';
                    }
                endforeach;
                wp_list_pages('title_li=&sort_column=menu_order&exclude=2,' . $page_exclusions);
                ?>

    I had to declare $page_exclusions. i also did inverse the construction of the string (first put the variable, then the comma).

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘[Resolved] Variables with "_" not working in foreach() loop in a theme’ is closed to new replies.