WordPress dynamic array

I have an issue creating array out of post title => post url values (of custom post type).

global $wp_query;
$type = 'qa';
$args=array(
  'post_type' => $type,
  'post_status' => 'publish'
);
$array = ();  
$my_query = new WP_Query($args);

if( $my_query->have_posts() ) {
      $title = get_the_title();
      $url = get_the_permalink();
      $data[] = array('key1'=>$title, 'key2'=>$url);
}

I tried this and couple other combinations but without too much luck.

Read More

End result I would like to have dynamic array that I’m able to search with ajax in jQuery.

That part is working with static array but I can’t manage to get it dynamic and working.

Exact format I need to get is:

$data = array(
 "Post 1 title" => "link post 1",
 "Post 2 title" => "link post 2",
 "Post 3 title" => "link post 3"
);

Many thanks for help!

Related posts

2 comments

  1. Just do:

    global $wp_query;
    $type = 'qa';
    $args=array(
      'post_type' => $type,
      'post_status' => 'publish'
    );
    $data = array();  
    $my_query = new WP_Query($args);
    
    if( $my_query->have_posts() ) {
          $title = get_the_title();
          $url = get_the_permalink();
          $data[$title] = $url;
    }
    
  2. Your loop is incomplete. You are trying to build your array before you are actually starting the loop. You need to move everything inside the loop and then build your array.

    Just a tip, because you are using a custom post type, rather use get_post_permalink to get the post permalink

    $type = 'qa';
    $args=array(
      'post_type' => $type,
      'post_status' => 'publish'
    );
    $my_query = new WP_Query($args);
    
    $data = array();
    if( $my_query->have_posts() ) {
        while ( $my_query->have_posts() ) {
          $title = get_the_title();
          $url = get_post_permalink();
          $data[$title] = $url;
        }
        wp_reset_postdata();
    }
    var_dump( $data );
    

Comments are closed.