wordpress wp_query code example
Example 1: wp query
<?php
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
}
wp_reset_postdata();
Example 2: wp_query
<?php
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
Example 3: wordpress custom php use wp query
if ( ! defined('ABSPATH') ) {
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );
Example 4: wp query search
$query = new WP_Query( array( 's' => 'keyword' ) );