Retain select value in select box

How are you all.
I am just struggling to make my custom select box keep retain select value in form when page is reload or user come on form via different navigation.

my select box is:

Read More
<?php
      $args = array('post_type'=> 'portfolio', 'posts_per_page' =>100, 'offset'=> 0);
      $myposts = get_posts( $args );
      foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
      <option value="<?php the_title(); ?>"><?php the_title(); ?></option>
      <?php endforeach;

in Core Php I know how to do this but in wordpress I am displaying post name in selectbox, so how can i achieve this, help would be appreciated….Thanks

Related posts

1 comment

  1. If I have understood correctly, you could use get_the_ID() and compare the value with get_queried_object_id() to archive this:

    $args       = array( 'post_type'=> 'portfolio', 'posts_per_page' =>100, 'offset'=> 0 );
    $myposts    = get_posts( $args );
    $current_id = get_queried_object_id();
    foreach ( $myposts as $post ) {
        setup_postdata( $post );
        printf(
            '<option%s>%s</option>',
            ( $current_id == get_the_ID() ) ? ' selected="selected"' : '',
            get_the_title()
        );
    }
    

Comments are closed.