• I want to get all posts from a category on the archive page

    //get current category id
    $current_cat = get_query_var('cat');
    
    $args = array( 'category' => $current_cat, 'post_type' =>  'post' );
    
    $postslist = get_posts( $args );
    
    foreach ($postslist as $post) :  setup_postdata($post); 
    
    $test_meta = get_post_meta($post->ID);
    
    echo the_title();
    
    endforeach;

    Each post has three custom fields which I need to create an array like the one below but I’m not sure how

    //create array
    $var = array(
        array("custom_field1", "custom_field2", "custom_field3"),
        array("custom_field1", "custom_field2", "custom_field3"),
    
    );
Viewing 1 replies (of 1 total)
  • See if this will do what you want (put your own meta_keys in the $keys_to_save array):

    //get current category id
       $current_cat = get_query_var('cat');
       $keys_to_save = array('key1','key2','key3');
       $args = array( 'category' => $current_cat, 'post_type' =>  'post' );
       $postslist = get_posts( $args );
       $var = array();
       foreach ($postslist as $post) :  setup_postdata($post);
          $test_meta = get_post_meta($post->ID);
          $vals = array();
          foreach ($keys_to_save as $key) {
             if (key_exists($key, $test_meta)) {
                $vals[] = $test_meta[$key][0];
             }
          }
          if ($vals) {
             $var[] = $vals;
          }
          echo the_title();
       endforeach;
       print_r('<pre>VAR:');print_r($var);print_r('</pre>');
Viewing 1 replies (of 1 total)

The topic ‘Array from custom fields’ is closed to new replies.