2017-01-05 4 views
7

Я попытался задать этот вопрос в сети Wordpress Devlopment без успеха, я пытаюсь отображать только 3 категории в постоянных ссылках для категорий пользовательского типа.Показывать только определенные категории в постоянных ссылках для пользовательского типа сообщения в WordPress

Сейчас структура Permalinks (то есть структура задается the theme i'm using и что я модифицирования через ребенка темы) выглядит следующим образом:

www.myfoodblog.com/recipes/the-post-title/ 
     ^  ^  ^ 
     root custom-post-type title 

некоторые вывешивают до 3-х категорий, которые я хотел бы отображение в постоянных ссылках, которые restaurant, users и admin, чтобы получить что-то вроде этого

www.myfoodblog.com/recipes/restaurant/the-post-title/ 

www.myfoodblog.com/recipes/users/the-post-title/ 

www.myfoodblog.com/recipes/admin/the-post-title/ 

оставив первоначальную структуру для сообщений, которые не в этих категориях.

Я пробовал использовать this plugin, но он отобразит пользовательскую категорию типа сообщения для всех сообщений.

Я также пробовал следовать инструкциям, приведенным в this question, но он не работает, никаких изменений в структуре постоянных ссылок не происходит.

Любые советы очень ценятся.

+0

Вы используете плагин для пользовательских почтовых типов или вы определить пользовательские после ввода себя? Я достиг этого на сайте, над которым я сейчас работаю, но все это настраиваемый код. – Daniel

+0

@ Даниэль. Я не использую плагин на данный момент, а CPT определяется темой, которую я использую. – Yenn

+0

Хорошо, так какая у вас структура постоянных отношений? Я предлагаю '/% category% /% postname% /' Wordpress должен показывать URL-адрес следующим образом: domain/CPT/category/postname – Daniel

ответ

2

Вы должны работать как с post_type_link и добавить rewrite rule

function recipes_post_link($post_link, $id = 0){ 
    $post = get_post($id); 
    if (is_object($post)){ 
     $terms = get_the_terms($post->ID, 'recipe-category'); 
     foreach($terms as $term) { 
      if($term->slug == 'restaurants' || $term->slug == 'users'){ 
       return str_replace(site_url()."/recipes" , site_url()."/recipes/".$term->slug , $post_link); 
      } 
     } 
    } 
    return $post_link; 
} 
add_filter('post_type_link', 'recipes_post_link', 1, 3); 

function custom_rewrite_basic() { 
    add_rewrite_rule('^recipes/(.+)/(.+)', 'index.php?recipe=$matches[2]', 'top'); 
} 
add_action('init', 'custom_rewrite_basic'); 
+0

Вот что я искал! Он отлично работает! Я не знал о функции 'add_rewrite_rule' и, похоже, это необходимо – Yenn

2

Create Post Type

add_action('init', 'codex_recipes_init'); 
/** 
* Register a recipes post type. 
* 
* @link http://codex.wordpress.org/Function_Reference/register_post_type 
*/ 
function codex_recipes_init() { 
    $labels = array(
     'name'    => _x('Recipes', 'post type general name', 'your-plugin-textdomain'), 
     'singular_name'  => _x('Recipe', 'post type singular name', 'your-plugin-textdomain'), 
     'menu_name'   => _x('Recipes', 'admin menu', 'your-plugin-textdomain'), 
     'name_admin_bar'  => _x('Recipe', 'add new on admin bar', 'your-plugin-textdomain'), 
     'add_new'   => _x('Add New', 'recipe', 'your-plugin-textdomain'), 
     'add_new_item'  => __('Add New Recipe', 'your-plugin-textdomain'), 
     'new_item'   => __('New Recipe', 'your-plugin-textdomain'), 
     'edit_item'   => __('Edit Recipe', 'your-plugin-textdomain'), 
     'view_item'   => __('View Recipe', 'your-plugin-textdomain'), 
     'all_items'   => __('All Recipes', 'your-plugin-textdomain'), 
     'search_items'  => __('Search Recipes', 'your-plugin-textdomain'), 
     'parent_item_colon' => __('Parent Recipes:', 'your-plugin-textdomain'), 
     'not_found'   => __('No recipes found.', 'your-plugin-textdomain'), 
     'not_found_in_trash' => __('No recipes found in Trash.', 'your-plugin-textdomain') 
    ); 

    $args = array(
     'labels'    => $labels, 
     'description'  => __('Description.', 'your-plugin-textdomain'), 
     'public'    => true, 
     'publicly_queryable' => true, 
     'show_ui'   => true, 
     'show_in_menu'  => true, 
     'query_var'   => true, 
     'rewrite'   => array('slug' => 'recipes/%type%'), 
     'capability_type' => 'post', 
     'has_archive'  => 'recipes', 
     'hierarchical'  => false, 
     'menu_position'  => null, 
     'supports'   => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments') 
    ); 

    register_post_type('recipes', $args); 
} 

Важно: взгляд на правила перезаписи: 'rewrite'=> array('slug' => 'recipes/%type%'),

Create Custom Taxonomy

// hook into the init action and call create_recipes_taxonomies when it fires 
add_action('init', 'create_recipes_taxonomies', 0); 

function create_recipes_taxonomies() { 

    // Add new taxonomy, NOT hierarchical (like tags) 
    $labels = array(
     'name'      => _x('Type', 'taxonomy general name', 'textdomain'), 
     'singular_name'    => _x('Type', 'taxonomy singular name', 'textdomain'), 
     'search_items'    => __('Search Types', 'textdomain'), 
     'popular_items'    => __('Popular Types', 'textdomain'), 
     'all_items'     => __('All Types', 'textdomain'), 
     'parent_item'    => null, 
     'parent_item_colon'   => null, 
     'edit_item'     => __('Edit Type', 'textdomain'), 
     'update_item'    => __('Update Type', 'textdomain'), 
     'add_new_item'    => __('Add New Type', 'textdomain'), 
     'new_item_name'    => __('New Type Name', 'textdomain'), 
     'separate_items_with_commas' => __('Separate types with commas', 'textdomain'), 
     'add_or_remove_items'  => __('Add or remove types', 'textdomain'), 
     'choose_from_most_used'  => __('Choose from the most used types', 'textdomain'), 
     'not_found'     => __('No types found.', 'textdomain'), 
     'menu_name'     => __('Types', 'textdomain'), 
    ); 

    $args = array(
     'hierarchical'   => true, 
     'labels'    => $labels, 
     'show_ui'    => true, 
     'show_admin_column'  => true, 
     'update_count_callback' => '_update_post_term_count', 
     'query_var'    => true, 
     'rewrite'    => array('slug' => 'type'), 
    ); 

    register_taxonomy('type', 'recipes', $args); 
} 

Add Filter Post Type Link

function recipes_post_link($post_link, $id = 0){ 
    $post = get_post($id); 
    if (is_object($post)){ 
     $terms = wp_get_object_terms($post->ID, 'type'); 
     if($terms){ 
      return str_replace('%type%' , $terms[0]->slug , $post_link); 
     } 
    } 
    return $post_link; 
} 
add_filter('post_type_link', 'recipes_post_link', 1, 3); 

Важно: В конце концов перейдите к параметрам постоянной ссылки и сбросьте его.

enter image description here

+0

Спасибо, что посмотрели. Тип сообщения и пользовательская таксономия уже определены темой и называются соответственно 'recipes' и' recipe-category'. Похоже, мне нужно будет использовать только вашу функцию 'recipes_post_link', но она не работает. Также похоже, что это сработает для каждой категории, пока я попрошу работать только с категорией НЕКОТОРЫЕ, что-то вроде 'if ($ terms == 'restaurant' || $ terms == 'users' || $ terms == 'admin') {do stuff} ' – Yenn

 Смежные вопросы

  • Нет связанных вопросов^_^