我想显示来自 CPT 的帖子,由高级自定义字段创建,其中自定义字段值与当前登录的用户名相同。
我该怎么办?
我用下面的functions.php尝试了它,在前端使用短代码实现它。但是它一直返回一个空白段落。
有人知道怎么做吗?这对我有很大帮助!
function facturen_shortcode($atts) {
$current_user = wp_get_current_user();
$args = array(
'post_type' => 'factuur',
'meta_query' => array(
array(
'key' => 'field_65bcf1c7d79ca',
'value' => $current_user->user_login,
'compare' => '=',
),
),
);
$query = new WP_Query($args);
ob_start();
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// Toon hier je berichten van het aangepaste berichttype
the_title();
echo '<br>';
}
} else {
// Geen berichten gevonden
}
wp_reset_postdata();
return ob_get_clean();
}
add_shortcode('facturen', 'facturen_shortcode');
我尝试使用functions.php函数和简码[facturen]创建它,但它只给了我一个空白段落。
您只需将 ACF 字段键 替换为 ACF 字段名称(slug):
例如,如果字段 slug 是“用户名”,您的代码将如下所示:
add_shortcode('facturen', 'facturen_shortcode');
function facturen_shortcode($atts) {
// Extract shortcode attributes
extract( shortcode_atts( array(
'user' => wp_get_current_user(),
), $atts, 'facturen' ) );
$query = new WP_Query( array(
'post_type' => 'factuur',
'post_status' => 'publish',
'meta_query' => array( array(
'key' => 'username',
'value' => $user->user_login,
'compare' => '=',
),),
) );
ob_start();
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// Toon hier je berichten van het aangepaste berichttype
the_title();
echo '<br>';
}
} else {
// Geen berichten gevonden
}
wp_reset_postdata();
return ob_get_clean();
}
使用另一种自定义帖子类型进行测试。短代码可以运行并显示标题。