Forums

Array to determine Subpage (5 posts)

  1. anthonyabraira
    Member
    Posted 1 year ago #

    I read in another closed thread the ability for someone to create a conditional based upon using the $post->post_parent feature. It looked like this:

    <?php if (5 == $post->post_parent) { echo 'this post has a parent of 5';
    	} elseif (63 == $post->post_parent) { echo 'this post has a parent of 63';
    	} elseif (97 == $post->post_parent) { echo 'this post has a parent of 97';
    	} elseif (104 == $post->post_parent) { echo 'this post has a parent of 104';
    	} elseif (82 == $post->post_parent) { echo 'this post has a parent of 82';
    	} else { }
    	?>

    This worked fine except that its a bit cumbersome. If its true for any of these 'parent' pages, then the subpage will have the same snippet of code. Where as now, I have to go in and place the same snippet for every condition. I tried this:

    <?php
    if ( 5 || 63 || 97 || 104 || 82 == $post->post_parent) { echo 'this post has a parent';
    } elseif ( is_page (array(5, 63, 97, 104, 82)) ) { echo 'no parent';
    } else {}
    ?>

    Doing that returned the same reply 'this post has a parent' regardless if it was the child post (page) or the parent.
    Can someone help a brother out?

  2. esmi
    Theme Diva & Forum Moderator
    Posted 1 year ago #

    Try replicating the format of the original code. You cannot use 5 || 63 || 97 etc.

  3. anthonyabraira
    Member
    Posted 1 year ago #

    @esmi — Not sure what you mean by that. I understand that I cannot use an "OR" statement but the question, what kind of statement will allow me to include an array of figures? Can you throw me an example of you mean.

  4. esmi
    Theme Diva & Forum Moderator
    Posted 1 year ago #

    if( 5 || 63 || 97 roughly translated comes out as "if 5 or 63 or 97".

    If 5 what? If 63 what?

    You have to use something like:

    if (5 == $post->post_parent || 63 == $post->post_parent etc. A more elegant option would be to create an array for comparison - eg:

    <?php
    $children = array(5, 63, 97, 104, 82);
    if( in_array($post->post_parent, $children) ) echo 'this post has a parent';
    elseif ( is_page (array(5, 63, 97, 104, 82)) ) { echo 'no parent';
    } else {}
  5. anthonyabraira
    Member
    Posted 1 year ago #

    @esmi —

    Thank you that did the trick. I thought the line:

    if ( 5 || 63 || 97 || 104 || 82 == $post->post_parent)

    was essentially saying that the numbers equal the "post_parent"

    Either way thanks again. What you sent worked beautifully.

Topic Closed

This topic has been closed to new replies.

About this Topic