[HELP] How to get WP_Query to work outside the loop?

I’m guessing this is probably something pretty simple, but working with WP\_Query is new for me. I’m trying to understand how to create a simple code snippet to query the WordPress posts table outside of any loop. I tried several attempts after reading the developer docs, to no avail. Obviously, my code below is a hodgepodge of spaghetti code because none of the “sample” code examples on [WP\_Query class reference page]) worked for me out of the box.

# EXPECTED OUTPUT

What I’m expecting as output: A list of 4 video posts with the title and content displayed for each. It should say:

Test Well Spot 3

Test Well Spot 2

Test Well Spot 1

\_CLONE to DIAGNOSE Episode Issue

​

# RECEIVED OUTPUT

Instead, I’m getting the title of the demo page 4 times:

# MY CODE

This is the code snippet I came up with to run in a shortcode widget in elementor:

function elsm_wp_query_simple() {

global $wbdb;
global $query;

$args = array(
‘numberposts’ => ‘4’,
‘post_type’ => ‘videos’,
);

$slider_posts = get_posts( $args );

if ( $slider_posts ) {
foreach ( $slider_posts as $post ) :

// First, setup post data
setup_postdata( $post );

// Second, define content to display ?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<!–setup_postdata() required for the_title() and the_content() to work–><?php
endforeach;

// Third, reset post data after end of the foreach function
wp_reset_postdata();
}

}
add_shortcode( ‘elsm_wp_query_demo’, ‘elsm_wp_query_simple’ );

What is wrong with my code, and how do I fix it?

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer