php - 简码 - WordPress
问题描述
我已经为帖子创建了简码,现在我需要在帖子/页面中对帖子进行简码。示例我在 post1 中嵌入了 post2,当我访问 post1 时,我看到了 post2,但是当我在 page1 中嵌入 post1 时,我看不到 post2
这是我到目前为止写的代码。
<?php
function getPostShortcode( $atts, $content = '' ) {
extract( shortcode_atts( array(
'id' => '',
'title' => ''
), $atts, 'post_shortcode' ) );
if ( empty( $atts['id'] ) )
return;
$loop = new WP_Query( array(
'post_type' => 'post',
'p' => $atts['id']
) );
ob_start();
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
$desc = ! empty( $atts['desc'] ) ? $atts['desc'] : get_the_content();
?>
<div class="post-single-shortcode-aka">
<h2><a href="#"><?php echo $title; ?></a></h2>
<p><?php echo $desc; ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
}
return ob_get_clean();
}
add_shortcode( 'post_shortcode', 'getPostShortcode' );
?>
解决方案
通常的做法是递归地“应用”短代码或过滤器。即每次你获得发布内容然后你“do_shortcode”。
在您的函数中,您可以使用“ get_post_field ”来获取帖子 ID 的内容、标题或摘录等。根据您希望输出的呈现方式,您可以使用apply_filters或do_shortcode;并且可能不需要 ob 缓冲。
function getPostShortcode( $atts, $content = '' ) {
extract( shortcode_atts( array(
'id' => '', 'title' => ''
), $atts, 'post_shortcode' ) );
if ( empty( $atts['id'] ) ) return;
// get_post_field can be used to get content, excerpt, title etc etc
$desc = get_post_field('post_content', $atts['id']);
$myEmbed = '<div class="post-single-shortcode-aka"><h2><a href="#">' . $title .'</a></h2><p>';
$myEmbed .= apply_filters('the_content',$desc) . '</p></div>';
// *** OR *** do_shortcode($desc) . '</p></div>';
return $myEmbed;
}
add_shortcode( 'post_shortcode', 'getPostShortcode' );
编辑:</div>
在上面的代码中 添加了缺失。
我已经测试过代码并且:如果帖子 A 包含[post_shortcode id=1234 title="Embed 1"]
,则“帖子 B”(id 1234”)嵌入在帖子 A 中。如果帖子 B 包含[post_shortcode id=3456 title="Embed 2"]
,则“帖子 C”(id 3456)也嵌入在帖子 B 和帖子 A 中。
推荐阅读
- html - 直到我将鼠标悬停在 SVG 线元素上才会呈现
- python - 如何在函数中使用 end="" with?
- tfs - TFS 2018 将 SharePoint 用于什么用途?
- r - diffinv 函数输出不是我想的那样
- python - 使用 sqlalchemy 的动态数据过滤器,它适用于给定值,但不适用于 NULL(None) 值
- flutter - 关于flutter的provider中出现的错误
- java - 运行 junit 时不支持的 major.minor 版本 52.0
- wordpress - 如何使用盐和密钥解密密码
- python - 在 python 中压缩和合并图像
- java - SimpleDateFormat.parse(date_string) 生成上一个日期