我有下面的WP Query,它运行得很好。基本上它是如何工作的,在我的网站上我有不同的关注领域。当你点击一个关注的领域,例如数学或科学。将显示所有与数学或科学相关的教师。
这是wp查询
<?php $schools = $post->ID; // the current post id ?>
<?php
$args = array(
'post_type' => 'teacher',
'meta_query' => array(
array(
'key' => 'areas_of_focus',
'value' => $schools,
'compare' => 'LIKE',
),
),
);
$schools_data_query = new WP_Query($args);
?>
<?php
if ( $schools_data_query->have_posts() ) {
echo '<ul>';
while ( $schools_data_query->have_posts() ) {
$schools_data_query->the_post();
//echo '<li>' . get_the_title() . '</li>';
//echo '<li>' . get_permalink() . '</li>'; ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
} else {
// no posts found
}
现在我想把它变成一个快捷代码。以下是我的想法,但并不奏效。无论我点击哪个领域的焦点,都会出现同样的老师。
function list_teacher_shortcode($atts){
global $post;
$schools = $post->ID;
$args = array(
'post_type' => 'teacher',
'meta_query' => array(
array(
'key' => 'areas_of_focus',
'value' => $schools,
'compare' => 'LIKE',
),
),
);
$schools_data_query = new WP_Query($args);
global $post;
$schools = $post->ID;
$content = '';
$content .= '<ul>';
while($schools_data_query->have_posts()) : $schools_data_query->the_post();
$content .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
$content .= '</ul>';
wp_reset_query();
return $content;
}
add_shortcode('list_teacher', 'list_teacher_shortcode');
我不太擅长这个后端编程,但我认为这与有关
全球$post;
$schools=$post->ID;
我把它列在两个不同的区域,但我试着从顶部和下部删除它,仍然得到了相同的结果。
您使用的全局$post;在你的短码中,它会占用页面上的最后一个帖子,所以你必须在你的简码中发送帖子id
echo do_shortcode('[list_teacher postID="'.$post->ID.'"]');
并将其放入list_tacher_shortcode函数中。
$a = shortcode_atts( array(
'postID' => '',
), $atts );
$postID = $a['postID'];
那么你就不需要这个代码了(你用了两次):
global $post;
$schools = $post->ID;
更新
您还可以在短代码中使用$query->the_post()和wp_reset_post_data()。点击此处了解更多信息https://codex.wordpress.org/Function_Reference/wp_reset_postdata
更新2完整代码
把它放在你想使用短码的地方
echo do_shortcode('[list_teacher postID="'.$post->ID.'"]');
这是您的完整短代码
function list_teacher_shortcode($atts){
$a = shortcode_atts( array(
'postID' => '',
), $atts );
$schools = $a['postID'];
$args = array(
'post_type' => 'teacher',
'meta_query' => array(
array(
'key' => 'areas_of_focus',
'value' => $schools,
'compare' => 'LIKE',
),
),
);
$schools_data_query = new WP_Query($args);
$content = '';
$content .= '<ul>';
while($schools_data_query->have_posts()) : $schools_data_query->the_post();
$content .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
$content .= '</ul>';
wp_reset_query();
return $content;
}
add_shortcode('list_teacher', 'list_teacher_shortcode');
更新3
此外,您还可以使用get_the_ID()。描述如下然后,你可以从shortcode函数中删除属性,函数的第一行应该是这样的:
$school = get_the_ID();