Search code examples
phpwordpresscountposts

Wordpress Post Count ( custom fields )


Trying to replicate this enter image description here http://www.chpcars.com/inventory/

to my website which is also using the same car listing plugin, Which is a modified post type Post_type=listing enter image description here

I have managed to use this script to display all cars in inventory but i cant select down to each model stock.

$posts = get_posts("post_type=listings"); 
$count = count($posts); 
 echo "$count";

here is an example of the tree layout for where these options for the post are. enter image description here


Solution

  • To filter WordPress posts based on any custom meta key (Such as maker's name here) you need to write the code such as:

    <?php
        $posts = get_posts(array(
            'post_type'     => 'listing',
            'meta_key'      => 'maker_name',
            'meta_value'    => 'BMW'
        ));
        echo count($posts);
    ?>
    

    Assuming that the meta_key for the Maker's Name is: maker_name If it is something else then pass that meta key name there

    If you do not know the meta key name for the field (E.g. Maker's name here) then you can use the below code to find all the meta key names in a WordPress post by just passing a post id.

    <?php 
       $meta = get_post_meta($post_id);
       var_dump($meta);
    ?>
    

    For further reference: Query posts by custom fields, Display all post meta keys and meta values of the same post ID in wordpress