我有一个简单的WP\\U查询,可以显示帖子:
<?php
function vertical_posts( $title, $category, $num_of_posts ) { ?>
<section class="vertical-posts">
<h2 class="title"><?php echo $title; ?></h2>
<div class="post-grid">
<?php
$args = array(\'category_name\' => $category, \'posts_per_page\' => $num_of_posts);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
?>
<article class="post">
<a class="post-thumbnail" href="<?php the_permalink(); ?>" aria-hidden="true" tabindex="-1">
<img src="<?php the_post_thumbnail_url(\'landscape-medium-1x\'); ?>" alt="<?php echo get_post_meta( get_post_thumbnail_id(), \'_wp_attachment_image_alt\', true ); ?>" loading="lazy">
</a>
<header class="entry-header">
<?php the_title(\'<h3 class="entry-title"><a href="\' . esc_url(get_permalink()) . \'" rel="bookmark">\', \'</a></h3>\'); ?>
<div class="entry-meta">
<?php
posted_on();
posted_by();
?>
</div>
</header>
</article>
<?php
}
}
else {
echo \'<p>Please add some posts.</p>\';
}
wp_reset_postdata();
?>
</div>
</section>
<?php
}
我在整个主题中都这样称呼它:
<?php vertical_posts( \'Answers\', \'answers\', 4 ); ?>
我希望能够在块编辑器或经典编辑器中使用短代码调用此函数。
我通过我的函数创建了短代码:
function register_shortcodes(){
add_shortcode(\'vertical-posts\', \'vertical_posts\');
}
add_action( \'init\', \'register_shortcodes\');
是否可以将函数参数传递给我的快捷码?
我的想法大致如下:
[vertical-posts \'Answers\', \'answers\', 4]
最合适的回答,由SO网友:Sam 整理而成
我为我的短代码创建了一个新函数:
<?php
function shortcode_posts( $atts ) {
$sc = shortcode_atts( array(
\'title\' => \'Answers\',
\'category\' => \'answers\',
\'num_of_posts\' => 4
), $atts );
?>
<section class="vertical-posts">
<h2 class="title"><?php echo $sc[\'title\']; ?></h2>
<div class="post-grid">
<?php
$args = array(\'category_name\' => $sc[\'category\'], \'posts_per_page\' => $sc[\'num_of_posts\']);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
?>
<article class="post">
<a class="post-thumbnail" href="<?php the_permalink(); ?>" aria-hidden="true" tabindex="-1">
<img src="<?php the_post_thumbnail_url(\'landscape-medium-1x\'); ?>" alt="<?php echo get_post_meta( get_post_thumbnail_id(), \'_wp_attachment_image_alt\', true ); ?>" loading="lazy">
</a>
<header class="entry-header">
<?php the_title(\'<h3 class="entry-title"><a href="\' . esc_url(get_permalink()) . \'" rel="bookmark">\', \'</a></h3>\'); ?>
<div class="entry-meta">
<?php
posted_on();
posted_by();
?>
</div>
</header>
</article>
<?php
}
}
else {
echo \'<p>Please add some posts.</p>\';
}
wp_reset_postdata();
?>
</div>
</section>
<?php
}
下面是我注册快捷码的方式:
function register_shortcodes(){
add_shortcode(\'posts\', \'shortcode_posts\');
}
add_action( \'init\', \'register_shortcodes\');
然后我会这样称呼这个短代码:
[posts title="Answers" category="answers" num_of_posts="4"]
有一个
great article from Kinsta 其中详细介绍了这一点。