Home > Software design >  How can I display all the published WordPress pages as dropdown options?
How can I display all the published WordPress pages as dropdown options?

Time:12-03

I am wanting to display all the published pages within my WordPress as a dropdown option.

I have tried the below code:

    <div >
    <?php
    $pages = get_pages();
    $posts = get_pages(array(
        'post_status'  => 'publish',
    ));
    $array_pages = (array)$posts;
    ?>
    <select name="per1" id="per1">
      <option selected="selected">Choose one</option>
      <?php
        foreach($array_pages as $name) { ?>
          <option value="<?= $name['name'] ?>"><?= $name['name'] ?></option>
      <?php
        } ?>
    </select>

But, it's not working for me. I am seeing something like this: https://prnt.sc/Jn-ZS98TmKFa

Can anyone share some insights please? Thanks!!

CodePudding user response:

get_pages() returns array of WP_Post objects. So to access post title or post ID you need to use ->. Eg, $object->post_title. See modified code below.

<div >
  <?php
  $pages = get_pages();
  $posts = get_pages(
    array(
        'post_status' => 'publish',
    )
  );
  $array_pages = (array) $posts;
  ?>
  <select name="per1" id="per1">
    <option selected="selected">Choose one</option>
    <?php
    foreach ( $array_pages as $page ) {
        ?>
        <option value="<?php echo esc_attr( $page->ID ); ?>"><?php echo esc_html( $page->post_title ); ?></option>
        <?php
    }
    ?>
  </select>
</div>
  • Related