我正在使用一个快捷码来显示自定义的帖子类型。快捷码包含一个属性,用于仅显示自定义帖子类型中特定类别的帖子,例如[常见问题解答类别=“旅行”]
对于每个短码,wordpress输出一组特定的html,包括id为“faq accordion”的div。对于每个短代码,我需要输出ID为“faq-accordion+1”的div,例如“faq-accordion 1”、“faq-accordion 2”、“faq-accordion 3”等。
我成功地在每个div中添加了一个数字,但由于某种原因,它最多只能添加到6,然后重复这些数字。
这是我的密码
add_shortcode( \'faq\', \'wpse105856_shortcode_callback\' );
function wpse105856_shortcode_callback( $atts ) {
extract( shortcode_atts( array(
\'category\' => \'\'
), $atts ) );
$args = array(
\'numberposts\' => -1,
\'orderby\' => \'menu_order\',
\'order\' => \'ASC\',
\'post_type\' => \'faq\'
);
if ( ! empty( $category ) ) {
$args[\'category_name\'] = $category;
};
$posts = get_posts( $args );
//Here is where I am trying to dynamically add a new number to the faq-accordion div
$num = 0;
foreach ( $posts as $post ) {
$faq = \'<div id="faq-accordion\'.++$num.\'">\'; //Open the container
};
foreach ( $posts as $post ) { // Generate the markup for each Question
$faq .= sprintf((\'<h3><a href="">%1$s</a></h3><div>%2$s</div>\'),
$post->post_title,
wpautop($post->post_content)
);
};
$faq .= \'</div>\'; //Close the container
return $faq; //Return the HTML.
};
最合适的回答,由SO网友:Kumar 整理而成
代码应改为
add_shortcode( \'faq\', \'wpse105856_shortcode_callback\' );
function wpse105856_shortcode_callback( $atts ) {
extract( shortcode_atts( array(
\'category\' => \'\'
), $atts ) );
$args = array(
\'numberposts\' => -1,
\'orderby\' => \'menu_order\',
\'order\' => \'ASC\',
\'post_type\' => \'faq\'
);
if ( ! empty( $category ) ) {
$args[\'category_name\'] = $category;
};
$posts = get_posts( $args );
//Here is where I am trying to dynamically add a new number to the faq-accordion div
$num = 0;
$faq = \'\';
$faq = \'<div class="question-wrapper">\';//wrapper div for all the questions
//Generate div for each question
foreach ( $posts as $post ) {
$faq .= \'<div id="faq-accordion\'.++$num.\'">\'; //Open the container
// Generate the markup for each Question
$faq .= sprintf((\'<h3><a href="">%1$s</a></h3><div>%2$s</div>\'),
$post->post_title,
wpautop($post->post_content)
);
$faq .= \'</div>\'; //Close the container
}
$faq .= \'</div>\';//close the wrapper
return $faq; //Return the HTML.
};
正如您所评论的,为了满足您在评论中的需要,您可以在div idlike中使用$post->ID
echo \'<div id="\'.$post->ID.\'">\';