gpt4 book ai didi

php - Wordpress WP_Query/get_posts where post_title equals 返回所有结果

转载 作者:可可西里 更新时间:2023-11-01 00:42:18 26 4
gpt4 key购买 nike

我创建了一个名为“片段”的自定义帖子类型,其中包含客户可以更改的数据片段,例如“地址”。

片段的标题都是唯一的: Custom Post Type

我创建了一个简单的函数来返回这些片段,但它运行不正常,我不确定为什么。

功能:

function get_snippet($snippet_title) {
$snippet_page = new WP_Query(array(
'post_type' => 'snippets',
'post_title' => $snippet_title
));
return $snippet_page->posts[0]->post_content;
}

下面是一个函数调用示例:

echo get_snippet('footer_address');

问题是:

它将始终返回所有片段,而不是按 post_title 过滤。

即使我使用 get_posts(),它也会始终以相同的顺序返回所有片段,并且不会返回基于 post_title 的单个片段。

结果相当于:

$snippet_page = new WP_Query(array(
'post_type' => 'snippets'
));

为什么不按“post_title”过滤?

谢谢

(我也在使用多站点)

这是我的自定义帖子类型初始化代码:

function snippets() {
$labels = array(
'name' => _x( 'Snippets', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Snippet', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Snippets', 'text_domain' ),
'name_admin_bar' => __( 'Snippets', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Snippets', 'text_domain' ),
'add_new_item' => __( 'Add New Snippet', 'text_domain' ),
'add_new' => __( 'Add New Snippet', 'text_domain' ),
'new_item' => __( 'New Snippet', 'text_domain' ),
'edit_item' => __( 'Edit Snippet', 'text_domain' ),
'update_item' => __( 'Update Snippet', 'text_domain' ),
'view_item' => __( 'View Snippet', 'text_domain' ),
'search_items' => __( 'Search Snippet', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
);
$args = array(
'label' => __( 'snippets', 'text_domain' ),
'description' => __( 'For custom snippets of code/data.', 'text_domain' ),
'labels' => $labels,
'supports' => array( ),
'hierarchical' => false,
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-tagcloud',
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => false,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => false,
'capability_type' => 'page',
);
register_post_type( 'snippets', $args );
}
add_action( 'init', 'snippets', 0 );

最佳答案

我知道这是一篇很老的帖子,但也许有人会像我今天一样在寻找解决方案。

原来你只需要使用'title'而不是'post_title'。

这是一个例子:

$author_id = 20;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit',
'title' => 'Reviewer Plugin - User review image',
'author' => $author_id,
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachedfile) {
$mediaIds = $attachedfile->ID .','. $mediaIds;
}
$mediaIds = rtrim($mediaIds,",");
}
print_r($mediaIds);

关于php - Wordpress WP_Query/get_posts where post_title equals 返回所有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31960199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com