我有下面的WP查询,它工作得很好。基本上它是如何工作的,在我的网站上,我有不同的重点领域。当你点击其中一个重点领域,例如数学或科学。所有与数学或科学相关的教师将被展示。
以下是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;
我把它列在两个不同的区域,但我试着把它从顶部和下部移除,结果仍然是一样的。
发布于 2015-12-04 15:53:16
您使用的是全局$post;在您的短代码中,它接受页面上的最后一篇文章,所以您必须在您的短代码中发送post id
echo do_shortcode('[list_teacher postID="'.$post->ID.'"]');并将其放入list_teacher_shortcode函数中。
$a = shortcode_atts( array(
'postID' => '',
), $atts );
$postID = $a['postID'];那么您就不需要这个代码了(您可以使用它两次):
global $post;
$schools = $post->ID;更新
您还可以在您的短代码中使用$query->the_post()和wp_reset_post_data()。更多信息,在这里后数据
更新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() description is 这里,然后可以从短代码函数中删除属性,函数的第一行应该如下所示:
$school = get_the_ID();https://stackoverflow.com/questions/34091989
复制相似问题