我有一个配方WP网站,它使用CPT来处理配方内容。
客户想要一个所有配方的A-Z目录列表。我找到Wordpress答案,发现以下代码满足了我的要求:
add_shortcode(\'recipe_list\', \'recipe_query\');
function recipe_query($atts, $content){
$args = array(
\'post_type\' => \'recipes\',
\'orderby\' => \'title\',
\'order\' => \'ASC\',
\'posts_per_page\' => -1
);
$query = new WP_Query( $args );
$dl = \'\';
$glossary_letter = \'\';
$active_letters = array( );
while ( $query->have_posts() ) {
$query->the_post();
$term_letter = strtoupper( substr( get_the_title(), 0, 1 ) );
if ( $glossary_letter != $term_letter ) {
$dl .= (count( $active_letters ) ? \'</ul>\' : \'\') . \'<li id="\' . $term_letter . \'"><span class="subheading">\' . $term_letter . \'</span><ul>\';
$glossary_letter = $term_letter;
$active_letters[] = $term_letter;
}
$dl .= \'<li><a href="\'.get_permalink().\'">\' . get_the_title() . \'</a></li>\';
}
$dl .= \'</ul></li>\';
$ul = \'<ul class="letters">\';
foreach ( array( \'0\', \'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\', \'8\', \'9\', \'A\', \'B\', \'C\', \'D\', \'E\', \'F\', \'G\', \'H\', \'I\', \'J\', \'K\', \'L\', \'M\', \'N\', \'O\', \'P\', \'Q\', \'R\', \'S\', \'T\', \'U\', \'V\', \'W\', \'X\', \'Y\', \'Z\' ) as $letter ) {
$ul .= \'<li>\' . (in_array( $letter, $active_letters ) ? \'<a href="#\' . $letter . \'">\' . $letter . \'</a>\' : $letter) . \'</li>\';
}
$ul .= \'</ul>\';
return \'<div id="glossary">\' . $ul . \'<ul class="definitions">\' . $dl . \'</ul></div>\';
}
现在有1020个配方,它似乎比其他页面运行得慢,而且由于我是一个弗兰肯斯坦程序员(有些来自这里,有些来自那里),我决定询问真正的php程序员。Is there a better, more efficient way to write the code?