Плагины для Wordpress: sCategory Permalink – выбор категории для построения постоянных ссылок

(WordPress) · English (34,841 views)

Я начинаю публиковать свои плагины для Wordpress, используемые в этом блоге, и сегодня это будет “sCategory Permalink”. Я являюсь ярым поклонником опции постоянных ссылок %category% Wordpress (и использую ее здесь), но она имеет одно существенное ограничение – когда опция выбрана, Wordpress использует категорию с наименьшим ID для построения постоянных ссылок! Представьте слудующий сценарий: у Вас есть категория “Development” (общая для всех заметок, касающихся разработки программного обеспечения), и несколько специфичных категорий, например, “PHP”, “AJAX”, “JavaScript”. У категории Development наибольший ID, потому для построения ссылок используются специфичные категории. Но однажды Вы решили начать изучать Ruby on Rails и писать об этом в Вашем блоге. Это проблема, поскольку при создании категории “Ruby on Rails”, ее ID будет больше, чем ID категории “Development”. Теперь Вам нужно принять решение: избегать публикации в обе категории сразу, или обновить ID категории “Development”. Последнее может быть выполнено двумя способами: удалить категорию из панели администрирования Wordpress и заново добавить ее (после этого Вам нужно пройтись по всем заметкам и добавить нужные в эту категорию), или обновить ID в базе данных (несколько таблиц, зависящих от ID категории). Но теперь Вы можете расслабиться! Просто скачайте и установите плагин!

Установка

  1. Загрузите и распакуйте файлы плагина в каталог wp-content/plugins/scategory_permalink.

  2. Включите плагин “sCategory Permalink” в Site Admin (Панель управления).

  3. Зайдите на страницу Options/Permalinks (Настройки/Постоянные ссылки) в Site Admin (Панель управления) и используйте опцию %scategory% в текстовом поле Custom (Задайте шаблон) (Вы можете глянуть здесь другие опции). В этом блоге я использую /%scategory%/%postname%/.

  4. Теперь на странице Write Post (Создание записи) рядом с чекбоксами категорий появятся переключатели:
    sCategory Permalink
    Выберите переключатель напротив категории, которая будет использоваться при построении постоянной ссылки.

  5. Наслаждайтесь!

Загрузка

Вы всегда можете загрузить последнюю версию плагина здесь.

17 Responses to this entry

Subscribe to comments with RSS

said on 08.02.2007 at 12.26 · Permalink

Amazing plugin. Are you planning a Wordpress 2.1 compatible version for the same?

said on 08.02.2007 at 12.34 · Permalink

Basically the radio buttons show up on the ‘edit post’ page, but not on write new post..

said on 08.02.2007 at 12.49 · Permalink

Here is the modification needed:-

Inside the function addOptions()

Replace:

1
strpos($_SERVER['REQUEST_URI'], 'post.php')

with:

1
strpos($_SERVER['REQUEST_URI'], 'post.php')||strpos($_SERVER['REQUEST_URI'], 'post-new.php')
Jangl
said on 08.02.2007 at 20.36 · Permalink

Огромное спасибо за статью!

Jangl
said on 08.02.2007 at 23.00 · Permalink

Только проблемки есть:

1) у меня не появилось переключателей рядом с чек боксом.

2) перестали работать комментарии, точнее ссылки на них… не находит такую страницу и саму страницу, где эта запись.

Jangl
said on 08.02.2007 at 23.17 · Permalink

А всё… разобрался… я не обновил .htaccess – сейчас всё ок.

said on 19.02.2007 at 15.23 · Permalink

Very prolific plugin. Concise and efficient code.
Works without any changes, even sitemaps builded
by another plugin uses new category in permalink.
Definetly a must have.

Now I’m going through all posts, assigning main cat, having fun.

said on 22.02.2007 at 1.16 · Permalink

Jayant, thanks for the patch. Will integrate it shortly. Plugin works with Wordpress 2.1 without any changes :-)

said on 23.02.2007 at 2.46 · Permalink

Great plugin! Works fine with WordPress 2.1 without changes.
Thanks for sharing!

Best wishes,
Caio Proiete

said on 21.03.2007 at 7.21 · Permalink

Thanks for the plugin! I’m wondering, if, in the case of such master-categories, it wouldn’t be easier to simply define certain categories that are excluded from the permalinks instead of having to define that for all posts?

Thanks!

said on 21.03.2007 at 8.03 · Permalink

Hi again, I’ve looked at your code and changed it by using this to select the first (in my case usually the only) category assigned to a post apart from the master-categories (here 1/16/32/33). There is a plugin that allows a main category that I am using. Having that and your category checkbox makes the admin panel unintelligible for the authors who aren’t admins. Too much stuff to do before posting a post. So I hope this simplifies it while still benefitting from your great idea and plugin -

::HLIGHT_BLOCK_1::

I’m sure this could be done far more elegantly by someone who’s more knowledgeable about php and WP, but it does the trick. Maybe someone else will benefit as well.

Thanks again!

said on 21.03.2007 at 8.04 · Permalink

Hmm, my code is not appearing – any formatting help to post it?

said on 22.03.2007 at 8.07 · Permalink

Tobias, sorry for inconvenience, I really forgot about Wordpress formatting … features. Currently I’ve adopted my code highlighting plugin to use it in comments. Check formatting tips above the textarea.

To insert code sample please use <code lang="php">$your_code = "here";</code>.

Thanks!

said on 26.03.2007 at 2.13 · Permalink

Hi Dmytro,

I’m one of the heavy users of your great plugin, and I’ve just found a bug on it, that occurs when someone posts a comment or a trackback on some post.

For some reason, the savePost function gets called on every new comment or trackback, and it ends up updating the post_meta table, and since there is no data to update, it updates to the first category of the post (thus loosing any child category you might have choosen to be the master).

I’ve solved it by just checking if we are on the “post” page, before attemp to save anything.

Here is the solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    /** Store category permalink in post meta */
    function savePost($post_ID) {
        /*
            Modified by Caio Proiete on 2007-03-25.
           
            Are we inside post.php or post-new.php?
        */

        if (strpos($_SERVER['REQUEST_URI'], '/post.php') || strpos($_SERVER['REQUEST_URI'], '/post-new.php')) {
            /*
                Yes, we are... It's Safe to save/update post_meta table
            */

            $category_permalink = $_POST['category_permalink'];

            $post_category = wp_get_post_cats('', $post_ID);
            if (isset($category_permalink)){
                $found = false;
                foreach ($post_category as $cid)
                    if ($cid == $category_permalink) {
                        $found = true;
                        break;
                    }
                if (!$found)
                    $category_permalink = $post_category[0];
                   
            } else
                    $category_permalink = $post_category[0];

            if (!update_post_meta($post_ID, '_category_permalink', $category_permalink))
                add_post_meta($post_ID, '_category_permalink',  $category_permalink, true);
        }          
    }

.

said on 30.03.2007 at 11.32 · Permalink

Thank you, guys
I have updated plugin to version 0.2.0, and you could get it
here (yeah, I have changed its location, but old URL would work too). Later I will publish post about other plugins.

said on 09.08.2007 at 13.52 · Permalink

After using your plugin I’m noticing some bugs. It’s doing the opposite of what the original Word Press was doing. However, it’s actually very manageable this way! Here is how my site is setup and how your plugin is helping it.

My site has 3 main categories, let’s just say “A, B, C” and in them they have sub categories, “cat, dog, mouse”

The main categories have low # category id’s because I created them first. The way the original wordpress would work was that it simply would call on the lowest id #, as you very well know. But now with your plugin, it’s calling on the higher id # which works like this:

If category A’s ID is #10
and category dog’s ID is #22 (and dog is a sub category of A) here is how they show up.

In word press it showed up as http://www.test.com/A/title.html

With your plugin it shows up as http://www.test.com/A/dog/title.html

And that is exactly how I wanted it! This makes the categories very manageable because now I can simply add a new category and it’ll work right away.

With that said, I have not tested if it works without sub categories. I personally have a gaming site, so something like http://www.test.com/news/xbox/ is what I want. Either way, I think this plugin is a life saver

Comments are closed

Comments for this entry are closed for a while. If you have anything to say – use a contact form. Thank you for your patience.