Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Use WP_Query in shortcode

Your have two major issues here

  • The string you are building is correct, but it gets overriden on each iteration of the loop, which at the end will only hold the info from the last post. You need to define your variable outside the loop and then concatenate your info to that variable across the entire loop in order for you to display all postdata from all posts

  • You are returning the wrong info. You are returning post id after the first iteration of the loop. Your should be returning your string with post info outside the loop

I think your code should look like this:

add_shortcode('sedan-tabs','build_sedan_tabs');
function build_sedan_tabs(){
    $querySedans="";
    $args1 = array(
        'post_type'  => 'inventory',
        'meta_key'   => 'vehicle-type',
        'meta_value' => 'Sedan',
        'posts_per_page' => '4'
    );
    $query1 = new WP_Query($args1);
    while ( $query1->have_posts() ) {
        $query1->the_post();
        $currentPostID = get_the_id();
        $vehicleImg = get_post_meta($currentPostID,'vehicle-images', true);
        $querySedans .=  '<div class="col-sm-3"><div class="display-car"><img src="' . $vehicleImg . '"/>' . 
        '<h3>' . get_post_meta($currentPostID,'vehicle-year', true) . ' ' . 
        get_post_meta($currentPostID,'vehicle-make', true) . ' ' . 
        get_post_meta($currentPostID,'vehicle-model', true) .'</h3><p>' .
        get_post_meta($currentPostID,'vehicle-mileage', true) . ' ' . 
        get_post_meta($currentPostID,'vehicle-transmission', true) . '<br /><strong>' . 
        get_post_meta($currentPostID,'vehicle-retail-price', true) . '</strong></p></div></div><a href="' . get_permalink($currentPostID, false) . '"></a>';
    }
    return $querySedans;
}

Related Posts:

  1. Get Current User Id Inside a Loop Returns 0 For a Shortcode
  2. Random order of WP_Query results with highest meta value
  3. Advanced Meta Query for Large Calendar Website (12k+ posts) (175k+ wp_postmeta rows)
  4. Remove echo from shortcode
  5. Is it possible to retrieve all posts with a certain value for metadata?
  6. Order a WP_Query by meta value where the value is an array
  7. How to work Woocommerce pagination inside shortcode?
  8. Delete post meta by serialized meta value
  9. Multiple Arrays for Custom Post Query using Boostrap accordions and ACF repeater fields
  10. Efficient way of querying for a “fallback” post?
  11. Shortcode content filter?
  12. How to filter posts by post format “standard” from wp-json api?
  13. Why is variable not working on custom sql query using wpdb?
  14. How to do multiple searches (with logical OR) in WP_Query in hook pre_get_posts?
  15. Create shortcodes within foreach loop (using array)
  16. Can’t search posts using WP_QUERY inside AJAX Function
  17. How to query for pages/post depending on slug?
  18. How can I use wp_query to show all product data using just the products ID?
  19. Custom Theme, Custom shortcode not working
  20. Trigger popup in a php if/else statement
  21. Custom page archive query by url var calling page twice on one of my custom queries?
  22. WordPress custom slug (endpoint) and compare all links
  23. How to query for posts with a null or blank post_name?
  24. Append HTML Using Shortcode
  25. WordPress pagination not working with search page
  26. get current custom post ID by WP_Query method
  27. Why is file_get_contents returning page source?
  28. Plugin CSS not enqueing
  29. How to securely provide a $_POST var in WP_Query with PHP 7?
  30. Using foreach loop breaks
  31. The text box have space character
  32. how to remove metadata from the posts of my blog?
  33. How can I create a list of page titles from custom meta values?
  34. Trying to remove post thumbnail with plugin
  35. Randomly Assign an Image’s Alt Text Based on Data From Post
  36. Create WP_Query to search for posts by their categories or their parent/child categories
  37. Different loop output every x posts in custom post type
  38. WP Query with custom Shortcode
  39. How to output a PHP file values by shortcode?
  40. Showing content from one page on another
  41. wp_query with cat not working
  42. How to use an associative array in post__in with WP_Query?
  43. If Query In Sidebar
  44. Showing a different gallery in a seperate post
  45. Recent Posts slider, using WP_Query(), loads duplicate sliders
  46. How to display posts by current user in a drop down
  47. Compare post-IDs within WP_Query? (Less than / Greater than)
  48. Create own WordPress shortcode gallery
  49. Get value from shortcode to do something
  50. How to use $query->set with post__in?
  51. Why do WP_Query results change after updating unrelated Advanced Custom Fields (ACF)?
  52. How to exclude category ID from Looper in WordPress
  53. Add a specific part of current category page url to shortcode
  54. How to display data from custom table in wordpress phpmyadmin
  55. Calculating a large number of MYSQL queries as customshort codes, slow
  56. Sort custom meta column by other meta value
  57. Store multiple custom field as post meta per post(css, js, html, 2 link) [closed]
  58. Loading the same WP_Query in two different wordpress .php templates
  59. How to prevent WP_Query function from returning all posts when empty?
  60. How to VAR_DUMP a $variable during checkout process (Is my product meta callable?)
  61. Dynamic content based on a URL parameter
  62. Display a specific category of products in shop page and disable code for specific actions
  63. Creating user status mode in WordPress
  64. WP_Query adds “(wp_posts.ID = ‘0’)” so no results are returned
  65. Need help with Google drive API [closed]
  66. WordPress Shortcodes.. printf is outputting a random number… Can’t figure out WHY?
  67. Colon is Missing In My Website Url in WordPress
  68. Add more button if more 8 items
  69. How to store post ID’s in cookie or session to display the same posts later
  70. WordPress, AJAX and pre_get_posts using conditional tags
  71. Custom shortcode outputs plain text instead of HTML at top of post
  72. How to use wp_add_inline_style for custom CSS added via shortcode?
  73. Get users that likes the post
  74. Pass php dynamic variable to shortcode
  75. How can I dynamically update the class in my shortcode?
  76. Creating own shortcode – echoeing php variable based on JS variable
  77. get_posts() and WP_query limits ‘AND’ conditions to a maximum of 6 for meta value queries in WordPress
  78. Exclude posts based on meta value
  79. Recent Posts Not Showing Only On A Specific Category Page [closed]
  80. Custom query, checking values of multiple meta keys
  81. Archive post by meta value + 24hours
  82. How create a Shortcode with hover and complex options
  83. Remove   from shortcode
  84. Displaying recent posts on static page with template-part via shortcode
  85. auto-populating custom nav with all items from custom post type
  86. wordpress 4.4 self hosted video (html5) doesn’t show
  87. inserting a post from an extern php file but post content doesn’t show on wp site
  88. do_shortcode with custom field
  89. WordPress update_post_meta updating with empty meta_value field [closed]
  90. How to Reference/Echo Variable from Another PHP Function
  91. Replace shortcode in substring
  92. How Can I use WP_Query to Only Display 1 Post from Custom Post Type if Query Returns Posts with Matching ID in Custom Field
  93. WordPress theme options error
  94. Shortcode to show the code
  95. Shortcode returns values in the wrong order
  96. Redirect to another page using contact form 7? [closed]
  97. Security for data obtained from the database
  98. Get URL from shortcode tag
  99. Embedding PHP in shortcode $content
  100. Fatal error: Call to a member function query() on a non-object
Categories PHP Tags php, post-meta, shortcode, wp-query
Complex WP_User_Query call fails on production server
How to pass many ids in post__in?

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress