我尝试按类别get_posts,获取只有一个标签或类别的帖子(幻灯片)。 在我的Wordpress主题中我有视差滑块,它使用自定义的帖子类型滑块,并执行此查询:
$args = array(
'post_type' => 'slider',
'posts_per_page' => -1,
'post_status' => 'publish',
'orderby' => $orderby,
'order' => $order,
'suppress_filters' => $suppress_filters
);
$slides = get_posts( $args );
这样我通过这个帖子类型得到所有帖子。在此数据转到循环之后:
foreach( $slides as $k => $slide ) {
$url = get_post_meta($slide->ID, 'my_slider_url', true);
$thumb_url = wp_get_attachment_image_src( get_post_thumbnail_id($slide->ID), 'slider-thumb');
$sl_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($slide->ID), 'full');
$caption = get_post_meta($slide->ID, 'my_slider_caption', true);
我创建了标签和类别的分类:
function my_post_type_slider() {
register_post_type( 'slider',
array(
'label' => theme_locals("slides"),
'singular_label' => theme_locals("slides"),
'_builtin' => false,
'exclude_from_search' => true, // Exclude from Search Results
'capability_type' => 'page',
'public' => true,
'show_ui' => true,
'show_in_nav_menus' => false,
'taxonomies' => 'slider_tag',
'rewrite' => array(
'slug' => 'slide-view',
'with_front' => FALSE,
),
'query_var' => 'slider', // This goes to the WP_Query schema
'menu_icon' => ( version_compare( $GLOBALS['wp_version'], '3.8', '>=' ) ) ? 'dashicons-slides' : PARENT_URL . '/includes/images/icon_slides.png',
'supports' => array(
'title',
'thumbnail',
'page-attributes',
)
)
);
register_taxonomy(
'slider_category',
'slider',
array(
'hierarchical' => true,
'label' => theme_locals("categories"),
'singular_name' => theme_locals("category"),
'rewrite' => true,
'query_var' => true
)
);
register_taxonomy(
'slider_tag',
'slider',
array(
'hierarchical' => false,
'label' => theme_locals("tags"),
'singular_name' => theme_locals("tag"),
'rewrite' => true,
'query_var' => true
)
);
}
add_action('init', 'my_post_type_slider');'
关于分类,我可以在管理面板中查看和使用它 - 我这样检查:
$category = get_terms( 'slider_category', $args ); print_r ($tags);
我可以得到:
Array (
[0] => WP_Term Object (
[term_id] => 46
[name] => 123
[slug] => 123
[term_group] => 0
[term_taxonomy_id] => 46
[taxonomy] => slider_category
[description] =>
[parent] => 0
[count] => 3
[filter] => raw
)
)
但是后来我尝试在带有args (category_name=>'nameofcat' or tag=>'tagname')
的get_posts或其他选项中使用它我得到了空幻灯片...
我也尝试使用' tax-query'并且仍然无法获得任何结果......
$args = array( 'tax_query' => array(
array(
'taxonomy' => 'slider_tag',
'field' => 'names',
'terms' => $slug_name,
),),
'posts_per_page' => -1,
'post_status' => 'publish',
'orderby' => $orderby,
'order' => $order,
'suppress_filters' => $suppress_filters
);
我可以使用get_posts通过cat / tag获取一些幻灯片数据吗? 我知道我可以使用全局WP_query,但这也没有好处,因为我需要重写周期。
答案 0 :(得分:1)
$args
的查询tax_query
错误。
这是正常的代码:
$args = array(
'numberposts' => -1,
'post_type' => 'slider',
'exclude' => $the_id,
'tax_query' => array(
array(
'taxonomy' => 'slider_tag',
'field' => 'slug',
'terms' => $slug_name,
)
)
);
$slides = get_posts( $args );