Php 如何在Wordpress中为空wp_查询编写更高效的回退
我有一个WooCommerce商店,我想在那里显示以下内容之一的特色图像和标题(按顺序):Php 如何在Wordpress中为空wp_查询编写更高效的回退,php,wordpress,woocommerce,Php,Wordpress,Woocommerce,我有一个WooCommerce商店,我想在那里显示以下内容之一的特色图像和标题(按顺序): 特色产品 如果没有特色产品,则粘贴帖子 如果没有粘性帖子,那么是最近的帖子 但我也想写高效的代码。我如何简化这个过程并删除冗余的PHP和HTML /* START FEATURED PRODUCT QUERY */ $args = array( 'posts_per_page' => 1, 'post_type' => 'product', 'meta_query' =
/* START FEATURED PRODUCT QUERY */
$args = array(
'posts_per_page' => 1,
'post_type' => 'product',
'meta_query' => array(
'key' => '_featured',
'value' => 'yes'
),
$query = new WP_Query( $args );
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post(); ?>
<a href="<?php the_permalink(); ?>" id="featured-blog-post">
<?php the_post_thumbnail('full');
the_title('<h2>', '<span>»</span></h2>' );
the_excerpt(); ?>
</a> <?php
} // end while
wp_reset_postdata();
} else {
/* START FALLBACK POST QUERY */
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts'),
'ignore_sticky_posts' => 1
);
$query = new WP_Query( $args );
while( $query->have_posts() ) {
$query->the_post(); ?>
<a href="<?php the_permalink(); ?>" id="featured-blog-post">
<?php the_post_thumbnail('full');
the_title('<h2>', '<span>»</span></h2>' );
the_excerpt(); ?>
</a> <?php
} // end while
wp_reset_postdata();
}
/*开始特色产品查询*/
$args=数组(
“每页帖子数”=>1,
“post_类型”=>“产品”,
“元查询”=>数组(
“键”=>“\u特征”,
“值”=>“是”
),
$query=新的WP\u查询($args);
如果($query->have_posts()){
而($query->have_posts()){
$query->the_post();?>
我正在编写一个类似的查询,我不确定您是否可以在Wordpress中使查询比您已有的查询效率更高。我唯一不同的做法是将POST的输出设置为一个函数,以便它调用相同的代码。这将使更新更容易
另外,因为在第一次查询中只查询一个元字段,所以我切换到一个简单的自定义字段查询
// Function to output posts
function output_posts( $query ){
while( $query->have_posts() ) {
$query->the_post();
echo '<a href="' . get_permalink() '" id="featured-blog-post">';
the_post_thumbnail( 'full' );
the_title( '<h2>', '<span>»</span></h2>' );
the_excerpt();
echo '</a>';
}
wp_reset_postdata();
}
// Featured query
$args = array(
'posts_per_page' => 1,
'post_type' => 'product',
'meta_key' => '_featured',
'meta_value' => 'yes',
);
$featured = new WP_Query( $args );
// If featured has posts
if( $featured->have_posts() ) {
// Output
output_posts( $featured );
// Else fallback
} else {
// Fallback query
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts'),
'ignore_sticky_posts' => 1,
);
$fallback = new WP_Query( $args );
// If fallback has posts
if ( $fallback->have_posts() ){
// Output
output_posts( $fallback );
}
}
//输出帖子的函数
函数输出\u posts($query){
而($query->have_posts()){
$query->the_post();
回声';
}
wp_reset_postdata();
}
//特色查询
$args=数组(
“每页帖子数”=>1,
“post_类型”=>“产品”,
“元密钥”=>“\u特征”,
“meta_值”=>“是”,
);
$featured=新的WP\u查询($args);
//如果你有帖子
如果($featured->have_posts()){
//输出
产出员额($);
//其他退路
}否则{
//回退查询
$args=数组(
“每页帖子数”=>1,
'post_uin'=>get_选项('sticky_posts'),
“忽略粘性帖子”=>1,
);
$fallback=新的WP\u查询($args);
//如果回退有帖子
如果($fallback->have_posts()){
//输出
产出员额(后备);
}
}