get_categories() Показать все категории для Custom Post Type

683 views
Skip to first unread message

Cyrill KALITA

unread,
Jul 26, 2012, 5:12:36 PM7/26/12
to ru-wor...@googlegroups.com
У меня есть custom post type, ioni_codex
Я пользуюсь встроенными категориями Wordpress для группировки коих 

Я хочу вывести все категории, используемые моим ioni_codex.

$myargs = array (
    'post_type' => 'ioni_codex'
); 
$categories = get_categories( $myargs );

Однако вместо этого мне выводится весь список всех категорий, в которых есть хоть один пост - не обращая внимания на указанный тип поста.

Что я делаю не так?

Yantar

unread,
Jul 26, 2012, 5:16:39 PM7/26/12
to ru-wor...@googlegroups.com
вроде параметр называется не post_type, а просто type?  http://codex.wordpress.org/Function_Reference/get_categories 
--
С уважением,
Яна Таран



2012/7/26 Cyrill KALITA <cyrill...@gmail.com>

Cyrill KALITA

unread,
Jul 26, 2012, 5:19:29 PM7/26/12
to ru-wor...@googlegroups.com
Согласен.
Но работает ни так ни эдак.

Yantar

unread,
Jul 26, 2012, 5:34:28 PM7/26/12
to ru-wor...@googlegroups.com
ну, судя по коду и не должно работать, как ни обидно :(
get_categories внутри себя http://core.trac.wordpress.org/browser/tags/3.4.1/wp-includes/category.php#L0 вызывает get_terms http://codex.wordpress.org/Function_Reference/get_terms  а у этой функции я не вижу ограничения по посттайпу
может, стоит воспользоваться отдельной таксономией для нужного посттайпа? ну или  свою функцию писать
--
С уважением,
Яна Таран



2012/7/26 Cyrill KALITA <cyrill...@gmail.com>
Согласен.
Но работает ни так ни эдак.


On Thursday, July 26, 2012 4:16:39 PM UTC-5, yantar wrote:
вроде параметр называется не post_type, а просто type?  http://codex.wordpress.org/Function_Reference/get_categories 
--
С уважением,
Яна Таран



2012/7/26 Cyrill KALITA <cyrill...@gmail.com>
У меня есть custom post type, ioni_codex
Я пользуюсь встроенными категориями Wordpress для группировки коих 

Я хочу вывести все категории, используемые моим ioni_codex.

$myargs = array (
    'post_type' => 'ioni_codex'
); 
$categories = get_categories( $myargs );

Однако вместо этого мне выводится весь список всех категорий, в которых есть хоть один пост - не обращая внимания на указанный тип поста.

Что я делаю не так?

--
http://groups.google.com/group/ru-wordpress

Cyrill KALITA

unread,
Jul 26, 2012, 5:41:06 PM7/26/12
to ru-wor...@googlegroups.com
Читаю.


On Thursday, July 26, 2012 4:34:28 PM UTC-5, yantar wrote:
ну, судя по коду и не должно работать, как ни обидно :(
get_categories внутри себя http://core.trac.wordpress.org/browser/tags/3.4.1/wp-includes/category.php#L0 вызывает get_terms http://codex.wordpress.org/Function_Reference/get_terms  а у этой функции я не вижу ограничения по посттайпу
может, стоит воспользоваться отдельной таксономией для нужного посттайпа? ну или  свою функцию писать
--
С уважением,
Яна Таран



2012/7/26 Cyrill KALIT
Согласен.
Но работает ни так ни эдак.

On Thursday, July 26, 2012 4:16:39 PM UTC-5, yantar wrote:
вроде параметр называется не post_type, а просто type?  http://codex.wordpress.org/Function_Reference/get_categories 
--
С уважением,
Яна Таран



2012/7/26 Cyrill KALITA
У меня есть custom post type, ioni_codex
Я пользуюсь встроенными категориями Wordpress для группировки коих 

Я хочу вывести все категории, используемые моим ioni_codex.

$myargs = array (
    'post_type' => 'ioni_codex'
); 
$categories = get_categories( $myargs );

Однако вместо этого мне выводится весь список всех категорий, в которых есть хоть один пост - не обращая внимания на указанный тип поста.

Что я делаю не так?

--
http://groups.google.com/group/ru-wordpress

Cyrill KALITA

unread,
Jul 26, 2012, 6:10:54 PM7/26/12
to ru-wor...@googlegroups.com
Я правильно понимаю, что мне надо будет определять post_type здесь?

* You can fully inject any customizations to the query before it is sent, as
* well as control the output with a filter.

Yantar

unread,
Jul 26, 2012, 6:15:09 PM7/26/12
to ru-wor...@googlegroups.com
Видимо да, только там какой-то замороченный выйдет запрос к базе, кажется.

--
С уважением,
Яна Таран



Message has been deleted

Yantar

unread,
Jul 27, 2012, 10:44:32 AM7/27/12
to ru-wor...@googlegroups.com
все уже придумано до нас, круто :)

--
С уважением,
Яна Таран



On Fri, Jul 27, 2012 at 4:17 PM, Cyrill KALITA <cyrill...@gmail.com> wrote:
А вот и переписаная функция

/* get terms limited to post type 
 @ $taxonomies - (string|array) (required) The taxonomies to retrieve terms from.
 @ $args  -  (string|array) all Possible Arguments of get_terms http://codex.wordpress.org/Function_Reference/get_terms
 @ $post_type - (string|array) of post types to limit the terms to
 @ $fields - (string) What to return (default all) accepts ID,name,all,get_terms.
 if you want to use get_terms arguments then $fields must be set to 'get_terms'
*/

function get_terms_by_post_type($taxonomies,$args,$post_type,$fields = 'all'){
    $args
= array(
       
'post_type' => (array)$post_type,
       
'posts_per_page' => -1
   
);
    $the_query
= new WP_Query( $args );
    $terms
= array();
   
while ($the_query->have_posts()){
        $the_query
->the_post();
        $curent_terms
= wp_get_object_terms( $post->ID, $taxonomy);
       
foreach ($curent_terms as $t){
         
//avoid duplicates
           
if (!in_array($t,$terms)){
                $terms
[] = $c;
           
}
       
}
   
}
    wp_reset_query
();
   
//return array of term objects
   
if ($fields == "all")
       
return $terms;
   
//return array of term ID's
   
if ($fields == "ID"){
       
foreach ($terms as $t){
            $re
[] = $t->term_id;
       
}
       
return $re;
   
}
   
//return array of term names
   
if ($fields == "name"){
       
foreach ($terms as $t){
            $re
[] = $t->name;
       
}
       
return $re;
   
}
   
// get terms with get_terms arguments
   
if ($fields == "get_terms"){
        $terms2
= get_terms( $taxonomies, $args );
       
foreach ($terms as $t){
           
if (in_array($t,$terms2)){
                $re
[] = $t;
           
}
       
}
       
return $re;
   
}
}


Оригинал -  взят отсюда:

--
http://groups.google.com/group/ru-wordpress

Cyrill KALITA

unread,
Jul 27, 2012, 11:23:04 AM7/27/12
to ru-wor...@googlegroups.com
Код надо чуть подчистить

К

Cyrill KALITA

unread,
Jul 27, 2012, 11:24:26 AM7/27/12
to ru-wor...@googlegroups.com
/* get terms limited to post type 
 @ $taxonomies - (string|array) (required) The taxonomies to retrieve terms from. 
 @ $args  -  (string|array) all Possible Arguments of get_terms http://codex.wordpress.org/Function_Reference/get_terms
 @ $post_type - (string|array) of post types to limit the terms to
 @ $fields - (string) What to return (default all) accepts ID,name,all,get_terms. 
 if you want to use get_terms arguments then $fields must be set to 'get_terms'
*/
 
function get_terms_by_post_type($taxonomies,$args,$post_type,$fields = 'all'){
    $args = array(
        'post_type' => (array)$post_type,
        'posts_per_page' => -1
    );
    $the_query = new WP_Query( $args );
    $terms = array();
    while ($the_query->have_posts()){
        $the_query->the_post();
        $curent_terms = wp_get_object_terms( $post->ID, $taxonomy);
        foreach ($curent_terms as $t){
          //avoid duplicates
            if (!in_array($t,$terms)){
                $terms[] = $t;

Roman Kokarev

unread,
Jul 27, 2012, 12:55:42 PM7/27/12
to ru-wor...@googlegroups.com
Но я надеюсь, вы не будете ничего менять в коде WP? :-)

2012/7/27 Cyrill KALITA <cyrill...@gmail.com>:
> --
> http://groups.google.com/group/ru-wordpress



--
Цените своё Время.
С уважением,
Roman Kokarev.

Cyrill KALITA

unread,
Jul 27, 2012, 12:58:30 PM7/27/12
to ru-wor...@googlegroups.com

Nope.

Functions.php

Кристина Лаптева

unread,
Jul 8, 2014, 1:53:35 PM7/8/14
to ru-wor...@googlegroups.com
пятница, 27 июля 2012 г., 1:12:36 UTC+4 пользователь Cyrill KALITA написал:

Столкнулась с такой же проблемой.расскажите поподробнее куда вставлять вами написанную функцию и что еще надо дописать чтобы работало. Спасибо

Reply all
Reply to author
Forward
0 new messages