我想通过自定义分类id获取自定义帖子,这是我的自定义代码。
function services_custom_init() {
$labels = array(
\'name\' => _x(\'services\', \'post type general name\'),
\'singular_name\' => _x(\'services\', \'post type singular name\'),
\'add_new\' => _x(\'Add New\', \'services\'),
\'add_new_item\' => __(\'Add New services\'),
\'edit_item\' => __(\'Edit services\'),
\'new_item\' => __(\'New services\'),
\'all_items\' => __(\'All services\'),
\'view_item\' => __(\'View services\'),
\'search_items\' => __(\'Search services\'),
\'not_found\' => __(\'No services found\'),
\'not_found_in_trash\' => __(\'No services found in Trash\'),
\'parent_item_colon\' => \'\',
\'menu_name\' => __(\'Services\')
);
$args = array(
\'labels\' => $labels,
\'public\' => true,
\'publicly_queryable\' => true,
\'show_ui\' => true,
\'show_in_menu\' => true,
\'query_var\' => true,
\'rewrite\' => true,
\'capability_type\' => \'post\',
\'has_archive\' => true,
\'hierarchical\' => false,
\'menu_position\' => null,
\'supports\' => array( \'title\', \'editor\', \'author\', \'thumbnail\', \'excerpt\', \'comments\' )
);
register_post_type(\'services\',$args);
}
add_action( \'init\', \'services_custom_init\' );
//hook into the init action and call create_book_taxonomies when it fires
add_action( \'init\', \'create_myservices_hierarchical_taxonomy\', 0 );
function create_myservices_hierarchical_taxonomy() {
$labels = array(
\'name\' => _x( \'myservices\', \'taxonomy general name\' ),
\'singular_name\' => _x( \'myservices\', \'taxonomy singular name\' ),
\'search_items\' => __( \'Search myservices\' ),
\'all_items\' => __( \'All myservices\' ),
\'parent_item\' => __( \'Parent myservices\' ),
\'parent_item_colon\' => __( \'Parent myservices:\' ),
\'edit_item\' => __( \'Edit myservices\' ),
\'update_item\' => __( \'Update myservices\' ),
\'add_new_item\' => __( \'Add New myservices\' ),
\'new_item_name\' => __( \'New myservices Name\' ),
\'menu_name\' => __( \'Myservices\' ),
);
// Now register the taxonomy
register_taxonomy(\'myservices\',array(\'services\'), array(
\'hierarchical\' => true,
\'labels\' => $labels,
\'show_ui\' => true,
\'show_admin_column\' => true,
\'query_var\' => true,
\'rewrite\' => array( \'slug\' => \'services\' ),
));
}
下面是按分类id获取自定义帖子的代码
<?php $custom_terms = get_terms(\'myservices\');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array(\'post_type\' => \'services\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'myservices\',
\'field\' => \'slug\',
\'terms\' => $custom_term->slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
echo \'<h2>\'.$custom_term->name.\'</h2>\';
while($loop->have_posts()) : $loop->the_post();
echo \'<a href="\'.get_permalink().\'">\'.get_the_title().\'</a>\';
<?php endwhile; ?>
}
}
?>