Situation
我创建了一个名为“横幅”的自定义帖子类型。在每一篇帖子上,我都能添加一幅特色图片。这将保存在我的数据库中,并将获得_thumbnail_id. 此外,在每个帖子编辑页面上,还有一个用于banner\\u url和target属性的自定义元框。在那里,我给我的横幅的链接,它应该去后,点击它的前端。目标属性将以正确的方式打开图像。这将正确发送到我的wpdb。
插件代码:
<?php
// function to show a banner using query of banner post type
function show_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
\'post_type\' => \'banners\',
\'meta_query\' => array(
\'relation\' => \'AND\',
array(
\'key\' => \'banner_link\',
\'value\' => \'https://www.mypage.com\'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) : while ( $get_banner->have_posts() ) : $get_banner->the_post();
$output = \'<div class="container" align="center"><a href="\'.get_post_meta( get_the_ID(), \'banner_link\', true ).\'"
target="\'.get_post_meta( get_the_ID(), \'target\', true).\'">\'.get_the_post_thumbnail().\'</a></div>\';
endwhile;
endif;
wp_reset_postdata();
return $output;
}
add_shortcode( \'banner\', \'show_banner\' );
//END
?>
第页。php
<?php echo do_shortcode("[banner]");?>
Question我使用meta\\u查询来选择url。它工作正常,显示正确的图像。链接和目标也可以正常工作。但我想要的是,我可以向do\\u快捷码回显添加一个缩略图id,然后在前端显示正确的图像,并在其周围显示正确的url和目标。
我希望有人能在正确的方向上帮助我。提前谢谢。
EDIT SOLUTION<特别感谢bynicolas帮我找到了正确的方向!
插件代码:
<?php
// function to show a banner using query of banner post type
function show_banner( $att ) {
// Set default $att values if none is provided
// $att is an array so access the shortcode value via $att[\'thumbnail_id\']
// in the [banner thumbnail_id="12"] shortcode
$atts = shortcode_atts(
array(
\'_thumbnail_id\' => \'\',
), $atts, \'banner\' );
//print_r(\'Thumbnail_id: \' . $att[\'_thumbnail_id\'] . \'<br>\');
//start by setting up the query
$get_banner = new WP_Query( array(
\'post_type\' => \'banners\',
)
);
//now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) :
while ( $get_banner->have_posts() ) : $get_banner->the_post();
$thumbnail_id = get_post_meta(get_the_ID(), \'_thumbnail_id\', true);
$image_url = get_post_meta(get_the_ID(), \'banner_link\', true);
$target = get_post_meta(get_the_ID(), \'target\', true);
if ($thumbnail_id === $att[\'_thumbnail_id\']) {
// print_r($thumbnail_id . \' \');
// print_r($image_url . \' \');
// print_r($target . \'<br>\');
$output = \'<div class="container" align="center"><a href="\'.get_post_meta( get_the_ID(), \'banner_link\', true ).\'"
target="\'.get_post_meta( get_the_ID(), \'target\', true).\'">\'.get_the_post_thumbnail().
\'</a></div>\';
}
endwhile;
endif;
wp_reset_postdata();
return $output;
}
add_shortcode( \'banner\', \'show_banner\' );
?>
第页。php
<?php echo do_shortcode(\'[banner _thumbnail_id="584"]\');?>
//584 is the thumbnail_id, so change that to your own thumbnail_id.