Různé typy příspěvků, taxonomie, metaboxy

„Custom post types in WordPress »“:http://justintadlock.com/archives/2010/04/29/custom-post-types-in-wordpress

„A refresher on custom taxonomies »“:http://justintadlock.com/archives/2010/06/10/a-refresher-on-custom-taxonomies

„Introducing WordPress 3 Custom Taxonomies »“:http://net.tutsplus.com/tutorials/wordpress/introducing-wordpress-3-custom-taxonomies/

„Innovative Uses of WordPress Post Types and Taxonomies „:http://wp.tutsplus.com/tutorials/theme-development/innovative-uses-of-wordpress-post-types-and-taxonomies/

„Custom Fields 101: Tips, Tricks, and Hacks »“:http://www.wpbeginner.com/wp-tutorials/wordpress-custom-fields-101-tips-tricks-and-hacks/

„Publish Action Hook for Custom Post Types »“:http://pippinspages.com/tutorials/publish-action-hook-for-custom-post-types/

„WordPress Custom Taxonomy Input Panels »“:http://www.shibashake.com/wordpress-theme/wordpress-custom-taxonomy-input-panels

„Revisiting Custom Post Types, Custom Taxonomies, and Permalinks »“:http://mondaybynoon.com/2011/05/20/revisiting-custom-post-types-taxonomies-permalinks-slugs/

„WordPress Custom Post Type Code Generator »“:http://themergency.com/generators/wordpress-custom-post-types/

**“Jak vytvořit vlastní metabox »“:http://www.deluxeblogtips.com/2010/04/how-to-create-meta-box-wordpress-post.html**

**“How To Create Custom Post Meta Boxes »“:https://www.smashingmagazine.com/2011/10/create-custom-post-meta-boxes-wordpress/**

Using custom meta box is a great way to make custom fields more friendly to users. It helps us much to add extra information to a post.

[* http://3.bp.blogspot.com/_Mt4qyhflsHY/S9XKl_VkMhI/AAAAAAAAAio/OK9s8GWmIaM/s1600/post-screen.png 645×525 *]

Viz též „Add A Meta Box In WordPress »“:http://wpshout.com/create-an-in-post-theme-options-meta-box-in-wordpress/

**Custom Post Type UI**
„http://wordpress.org/extend/plugins/custom-post-type-ui/“:http://wordpress.org/extend/plugins/custom-post-type-ui/
„http://webdevstudios.com/support/wordpress-plugins/“:http://webdevstudios.com/support/wordpress-plugins/

This plugin provides an easy to use interface to create and administer custom post types in WordPress. Plugin can also create custom taxonomies. This plugin is created for WordPress 3.0.

**WP Easy Post Types**
„http://wordpress.org/extend/plugins/easy-post-types/“:http://wordpress.org/extend/plugins/easy-post-types/

This plugin lets you take advantage of the WordPress 3.0 custom post type feature, and create your own post type. The plugin allows you to add a set of fields attached to your new post type, so that in the edit and add new windows a new box will show with the fields defined. Each field added will be saved in the WordPress Database as a custom field, so that you can take advantage of the standard WordPress query rules to list your content on the page template.
Not only can you create and manage new post types but you can create and manage custom fields and meta boxes associated with a particular post type. It comes with a built-in date picker field to help with post types that are date-specific. Another key feature giving this plugin loads of potential is that it allows you manage the admin display of your created post types. For instance, if you wanted a custom field to show up in the posts list screen, you can do that.

**Post Type Switcher**
„http://wordpress.org/extend/plugins/post-type-switcher/“:http://wordpress.org/extend/plugins/post-type-switcher/

A simple way to change a post type in WordPress (one at a time). Any combination is possible, even custom post types.

– Page to Post
– Post to Page
– Post to Custom
– Post to revision/attachment/navigation menu is possible but turned off by default

**Convert Post Types**
„http://wordpress.org/extend/plugins/convert-post-types/“:http://wordpress.org/extend/plugins/convert-post-types/

This is a utility for converting lots of posts or pages to a custom post type (or vice versa). You can limit the conversion to posts in a single category or children of specific page. You can also assign new taxonomy terms, which will be added to the posts‘ existing terms.

*Další informace:*

„A WordPress forum plugin using custom post types“:http://justintadlock.com/archives/2010/07/16/a-wordpress-forum-plugin-using-custom-post-types
„The Essential Guide to WordPress 3.0 Custom Taxonomies“:http://www.1stwebdesigner.com/wordpress/essential-guide-wordpress-custom-taxonomies/

„First Impressions of Custom Post Type“:http://wpengineer.com/impressions-of-custom-post-type/
„Function Reference/register post type“:http://codex.wordpress.org/Function_Reference/register_post_type
„Custom Post Types in WordPress 2.9“:http://www.hostscope.com/templature/custom-post-types-in-wordpress-2-9/
„How To Make WordPress An CMS With Different Post Types“:http://www.knowtebook.com/how-to-make-wordpress-an-cms-with-different-post-types-1627.htm
„Developing Post Types Plugin with WordPress“:http://www.packtpub.com/article/developing-post-types-plugin-with-wordpress
„How to Set Up Custom WordPress Category Templates“:http://mattmedia.net/2007/10/09/how-to-set-up-custom-wordpress-category-templates-in-four-easy-steps/
„Creating single post templates in WordPress“:http://justintadlock.com/archives/2008/12/06/creating-single-post-templates-in-wordpress
„WordPress Single Post Templates“:http://www.nathanrice.net/blog/wordpress-single-post-templates/

Konfigurace

Wp-config.php is the single most important file in your entire WordPress installation. This file can be used to configure database functionalities, enhance performance, and improve security on all WordPress powered websites and blogs.

**Debugging WordPress**

For developers, WordPress has this awesome debugging feature which allows them to find errors, and deprecated functions. By default, this function is set to false, but in the development mode, developers should have it enabled.

/—code php
define(‚WP_DEBUG‘, false); // disable debugging mode by default
define(‚WP_DEBUG‘, true); // enable debugging mode
\—

**Blog/Site Address**

In your WordPress Settings, you specify the WordPress address and the site address. Those are added in your database, and every time the developer calls it in the template, it is running a database query. In WordPress 2.2, these two settings were introduced to override the database values without changing them:

/—code php
define(‚WP_HOME‘, ‚http://www.wpbeginner.com‘);
define(‚WP_SITEURL‘, ‚http://www.wpbeginner.com‘);
\—

By adding these in your wp-config.php, you are reducing the number of database queries thus increasing your site’s performance.

**Override File Permissions**

You can override file permissions, if your host has restrictive permissions for all user files. Most of you do not need this, but it exists for those who need it.

/—code php
define(‚FS_CHMOD_FILE‘, 0755);
define(‚FS_CHMOD_DIR‘, 0644);
\—

**Post Revisions**

In the recent versions of WordPress, there is a super awesome feature called Post Revisions. This function auto-saves posts just incase if your browser crash, or something else happen. It also allows users to restore back to previous versions if they don’t like the changes and so on. While a lot of us love this feature, some of us really hate it with a passion. This function has numerous configuration, so you can make it work just right for you.
By default WordPress saves post every 60 seconds, but if you think that is way too much, then you can modify it to your likings with this configuration:

/—code php
define(‚AUTOSAVE_INTERVAL‘, 120); // in seconds
\—

Some posts have 10s, 20s, or even 100 post revisions depending on the blog owner. If you think that feature annoys you, then you can limit the number of revisions per post.

/—code php
define(‚WP_POST_REVISIONS‘, 5);
\—

You can use any integer you like there.

If none of the settings above satisfies you, then you can simply disable the post revisions feature by adding this function:

/—code php
define(‚WP_POST_REVISIONS‘, false);
\—

**WordPress Trash Feature**

In WordPress 2.9, there was a new “Trash” feature added to the core. This feature works just like the recycling bin, so instead of deleting the post permanently, you would send it to the trash. This helped those users who accidently click on Delete button, and it can be any of us. The bad part about this trash feature is that you have to empty the trash regularly. By default the trash empties itself every 30 days. You can modify that by using the following function:

/—code php
define(‚EMPTY_TRASH_DAYS‘, 7 ); //Integer is the amount of days
\—

**FTP/SSH Constants**

By default, WordPress allow you to upgrade plugins, and WordPress core versions from within the backend. There are some hosts that requires an FTP or SSH connection everytime you try to upgrade, or install a new plugin. By using the codes below, you can set the FTP or SSH constants and never have to worry about it again.

/—code php
// forces the filesystem method: „direct“, „ssh“, „ftpext“, or „ftpsockets“
define(‚FS_METHOD‘, ‚ftpext‘);
// absolute path to root installation directory
define(‚FTP_BASE‘, ‚/path/to/wordpress/‘);
// absolute path to „wp-content“ directory
define(‚FTP_CONTENT_DIR‘, ‚/path/to/wordpress/wp-content/‘);
// absolute path to „wp-plugins“ directory
define(‚FTP_PLUGIN_DIR ‚, ‚/path/to/wordpress/wp-content/plugins/‘);
// absolute path to your SSH public key
define(‚FTP_PUBKEY‘, ‚/home/username/.ssh/id_rsa.pub‘);
// absolute path to your SSH private key
define(‚FTP_PRIVKEY‘, ‚/home/username/.ssh/id_rsa‘);
// either your FTP or SSH username
define(‚FTP_USER‘, ‚username‘);
// password for FTP_USER username
define(‚FTP_PASS‘, ‚password‘);
// hostname:port combo for your SSH/FTP server
define(‚FTP_HOST‘, ‚ftp.example.org:21‘);
\—

**Auto Database Optimization**

In WordPress 2.9, there was a feature added called Automatic Database Optimization. To enable this feature, you would need to use the following function:

/—code php
define(‚WP_ALLOW_REPAIR‘, true);
\—

Once activated, you can see the settings on this page: http://www.yoursite.com/wp-admin/maint/repair.php
The user does not need to be logged in to access this functionality when this define is set. This is because its main intent is to repair a corrupted database, Users can often not login when the database is corrupt. So once you are done repairing and optimizing your database, make sure to remove this from your wp-config.php.

**Increase PHP Memory Limit**

There is a common WordPress Memory Exhausted Error that users have seen when activating some plugin. You can increase the PHP Memory Limit through wp-config.php file. Simply paste the code below:

/—code php
define(‚WP_MEMORY_LIMIT‘, ’64M‘);
\—

Note: This feature may not work with some web hosts.

**WordPress Error Log**

For developers, it is useful to have an error log for a site. You can easily create a simple error log for a WordPress powered website by using wp-config.php file. First create a file called “php_error.log”, make it server-writable, and place it in the directory of your choice. Then edit the path in the third line of the following code:

/—code php
@ini_set(‚log_errors‘,’On‘);
@ini_set(‚display_errors‘,’Off‘);
@ini_set(‚error_log‘,’/home/path/domain/logs/php_error.log‘);
\—

Also, for an error log, you should instead use these constants:

/—code php
define( ‚WP_DEBUG‘, true ); // Enables error reporting.
define( ‚WP_DEBUG_DISPLAY‘, false ); // Hides the errors.
define( ‚WP_DEBUG_LOG‘, true ); // Logs errors to wp-content/error.log (or use @ini_set(‚error_log‘) )
\—

**Automatické vysypání koše**

/—code php
define(‚EMPTY_TRASH_DAYS‘, 30 ); // Vysypání koše po 30 dnech
\—

**Přesunutí složky WP-Content**

/—code php
define( ‚WP_CONTENT_DIR‘, $_SERVER[‚DOCUMENT_ROOT‘] . ‚/newlocation/wp-content‘ );
\—

nebo

/—code php
define( ‚WP_CONTENT_URL‘, ‚http://www.yourwebsite.com/newlocation/wp-content‘ );
\—

cesta k adresáři s pluginy

/—code php
define( ‚WP_PLUGIN_DIR‘, $_SERVER[‚DOCUMENT_ROOT‘] . ‚/newlocation/wp-content/plugins‘ );
define( ‚WP_PLUGIN_URL‘, ‚http://www.yourwebsite.com/newlocation/wp-content/plugins‘);
\—

**Pokud nefunguje localhost a neznáme jméno DB serveru**

/—code php
define(‚DB_HOST‘, $_ENV{DATABASE_SERVER});
\—

/—code php
define(‚DB_HOST‘, $_ENV{DATABASE_SERVER});
\—

Nezapomeňte konfigurační soubor „zabezpečit“:https://wordpresso.ovx.cz/vyladeni-nove-instalace-wordpressu/.

Jak deaktivovat pluginy mimo administrační rozhraní

If you installed the wrong plugin (usually unsupported or mis-configured but also malicious plugins) and got the dreaded blank screen of death with errors, don’t panic. Even though the Admin panel may not work, there’s still a emergency solution by executing one simple query in the database.
Simply execute this SQL query (perhaps through PHPMyAdmin):

/—code php
// WP 2.9 and earlier
UPDATE wp_options SET option_value = “ WHERE option_name = ‚active_plugins‘;

// WP 2.9 and later:
UPDATE wp_options SET option_value = ‚a:0:{}‘ WHERE option_name = ‚active_plugins‘;
\—

Alternatively, if it’s not possible to change the database, **you can also simply rename the /wp-content/plugins/ folder to disable all plugins**.
This will disable all plugins in the WordPress installation. Rename it back after.
You just have to go back and enable all the working plugins and deleting the non-functional one.

Úprava administračního rozhraní prostřednictvím functions.php

**Vlastní logo na nástěnce**

/—code php
// hook the administrative header output
add_action(‚admin_head‘, ‚my_custom_logo‘);

function my_custom_logo() {
echo ‚

‚;
}
\—

**Změna obsahu patičky**

/—code php
function change_footer_admin () {
echo ‚Pohání: WordPress | Vytvořeno: OVX.cz‚;
}

add_filter(‚admin_footer_text‘, ‚change_footer_admin‘);
\—

**Přidání vlastních odkazů**

/—code php
function mytheme_admin_bar_render() {
global $wp_admin_bar;
$wp_admin_bar->add_menu( array(
‚parent‘ => ‚new-content‘, // use ‚false‘ for a root menu, or pass the ID of the parent menu
‚id‘ => ‚new_media‘, // link ID, defaults to a sanitized title value
‚title‘ => __(‚Media‘), // link title
‚href‘ => admin_url( ‚media-new.php‘), // name of file
‚meta‘ => false // array of any of the following options: array( ‚html‘ => “, ‚class‘ => “, ‚onclick‘ => “, target => “, title => “ );
));
}
add_action( ‚wp_before_admin_bar_render‘, ‚mytheme_admin_bar_render‘ );
\—

„Různé úpravy administrační lišty »“:http://digwp.com/2011/04/admin-bar-tricks/

Jak přidat tagy ke stránkám nebo stránky zařadit do rubriky

Možnost tagování stránek docílíme zaregistrováním příslušných *post_tag* a *category* taxonomií prostřednictvím funkce „register_taxonomy_for_object_type function“:http://codex.wordpress.org/Function_Reference/register_taxonomy_for_object_type:

/—code php
// Add to the admin_init hook of your theme functions.php file
register_taxonomy_for_object_type(‚post_tag‘, ‚page‘);
register_taxonomy_for_object_type(‚category‘, ‚page‘);
\—

která rovněž zobrazí příslušné metaboxy pro přidávání tagů a zařazení stránky do rubriky v administraci.

[* http://wordpress.shibashake.com/wp-content/uploads/2010/09/add-wordpress-tags-categories2-520×325.jpg *]

Abychom pak stránku v rámci přiřazené rubriky či tagů (štítků) zobrazili, přidáme do *functions.ph* filtr:

/—code php
// Add to the init hook of your theme functions.php file
add_filter(‚request‘, ‚my_expanded_request‘);

function my_expanded_request($q) {
if (isset($q[‚tag‘]) || isset($q[‚category_name‘]))
$q[‚post_type‘] = array(‚post‘, ‚page‘);
return $q;
}
\—

ev. pluginem **Tag Pages**
„http://wordpress.org/plugins/tag-pages/“:http://wordpress.org/plugins/tag-pages/

This plugin adds the ‚post_tag‘ taxonomy to the Page post type. This enables the tags metabox in the New or Edit Page interface. To show tagged Pages on a tags archive page or in a feed, it uses the ‚pre_get_posts‘ hook to change the post_type query parameter to ‚any‘.

Snadné stránkování bez pluginu

Pokud chcete své příspěvky ve WordPress stránkovat, musíte obvykle sáhnout po nějakém pluginu. Což rozhodně není ideální řešení. Stránkování obsahu je prostě základní funkce. Je škoda, že to WordPress neumí bez nějakého zbytečného pluginu!

Jenže on to umí. V administraci se stránkování obsahu používá téměř všude. Což mimo jiné znamená, že na to existuje funkce. Stačí ji tedy jen dobře použít:

$pagination = array(
	'base' => get_pagenum_link().'%_%',
	'format' => 'page/%#%',
	'total' => ceil($wp_query->found_posts / get_settings('posts_per_page')),
	'current' => absint( get_query_var( 'paged' ) ),
	'show_all' => false,
	'prev_next' => true,
	'prev_text' => __('« Previous'),
	'next_text' => __('Next »'),
	'end_size' => 3,
	'mid_size' => 5,
	'type' => 'plain',
	'add_args' => false,
	'add_fragment' => ''
);

echo paginate_links($pagination);

Funkce paginate_links má řadu vstupních parametrů, které jsou podrobně popsány v dokumentaci.

Nejdůležitější je samozřejmě total – měl by obsahovat počet stránek. Ten jsem vypočítal jako zaokrouhlený podíl celkového počtu příspěvku a počtu příspěvků na stránku (tohle se nastavuje se v administraci).

Parametr current by měl obsahovat číslo aktuálně prohlížené stránky. Zjistíte jej snadno pomocí get_query_var. Další dva neméně důležité parametry jsou baseformat – pomocí kterých se tvoří URL odkazu.

Base by měl obsahovat základní část URL. Což je ta část, které se při procházení jednotlivých stránek nemění. Nenapadl mě lepší způsob, než zavolat funkci get_pagenum_link. Řetězec %_% bude při tvorbě URL nahrazen obsahem parametru format.

Format je ono samotné stránkování. Měl by obsahovat tu část URL, která se bude měnit. V mém příkladu využívám tzv. hezké URL. Takže číslo stránky je očekávané za page. Řetězec %#% bude nahrazen čísly. Výsledná URL tak bude vypadat například takto http://www.nabito.net/page/2

Ostatní parametry jsou spíš doplňkové.

Zvýraznění právě hledaných slov

Několik následujících řádků kódu obalí všechna právě vyhledávaná klíčová slova do značky STRONG (class search-keyword). Kód je možné vložit do function.php ve Vašem template. Nebo jej můžete vložit rovnou do search.php někde těsně za volání funkce get_header(). Předpokladem samozřejmě je, že využíváte standardních vyhledávacích funkcí WordPress.

function omSearchHeighlight($text)
{
$keys = explode(" ", get_search_query());
$text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-keyword">\0</strong>', $text);
return $text;
}

add_filter('the_title','omSearchHeighlight');
add_filter('the_content','omSearchHeighlight');
add_filter('the_excerpt','omSearchHeighlight');

// nezapomeňte strong element nastylovat např.
// strong.search-keyword {background: #f3ff0f!important; color:#000!important;}

Výsledkem je malé, ale užitečné, vylepšení výsledků vyhledávání, které Vás navíc nestojí téměř žádnou námahu. Ještě malá poznámka na závěr: Kód nedbá na velikost písmen.

Odstranění části admin menu

WordPress není systém, který by nabízel přebujelé množství funkcí. Administrace je jednoduchá a přehledná. Přesto se občas může hodit, nějakou tu funkci natvrdo schovat před nenechavým klikáním zákazníka.

Celé administrátorské menu je uložené v souboru wp-admin/menu.php – do toho samozřejmě sahat nebudeme. Tento soubor nám postačí k tomu, abychom zjistili jak se menu tvoří. Menu je uložené ve dvou polích: $menu$submenu. Obě tyto pole můžeme svobodně upravit, protože se jedná o globální proměnné. Svobodně upravit znamená například část vymazat. Úpravu těchto polí musíme samozřejmě stihnout před tím, než se pole použijí při vykreslování menu.

Do souboru function.php, který najdete ve wp-content/template/cokoliv, stačí přidat nový hook a funkci:

function edit_remove_menu() {
  global $menu, $submenu;
  unset($menu[25]); // odstraní z menu komentáře
  unset($menu[15]); // odstraní z menu odkazy

  // dale je mozne upravit také submenu
  unset($submenu['edit.php'][15]); // odstraní Příspěvky / Štítky
}

add_action('admin_menu', 'edit_remove_menu');

Na závěr malé upozornění, jednotlivé skryté funkcionality nadále fungují, pouze nejsou vidět v menu. Takže pokud znáte tu správnou adresu, můžete se k nim normálně dostat.

Dvě různé WordPress šablony na jednom blogu

Tento článek volně navazuje na můj předchozí článek s názvem: Speciální šablona pro konkrétní rubriku, stránku či příspěvek.

V něm je představeno řešení č. 1, kdy pro kategorii, příspěvek nebo stránku vytvoříme speciální šablonu pomocí tzv. template slugs, kdy vestavěná hierarchie užitích šablon, vždy nejdříve kontroluje o jaký obsah se jedná (například kategorie, stránka) a poté hledá existující šablonu v konkrétním pořadí.

Pro kategorii s názvem “Moje Kategorie” a s id=3 vypadá rozhodovací proces takto:

1) jde o kategorii? Ano
2) Existuje v šabloně soubor s názvem category-moje-kategorie.php? Ano, tak jej použij. Ne, bod 3
3) Existuje v šabloně soubor s názvem category-3.php? Ano, tak jej použij. Ne, bod 4.
4) Existuje v šabloně soubor s názvem category.php? Ano, tak jej použij. Ne, bod 5.
5) Existuje v šabloně soubor s názvem archive.php? Ano, tak jej použij. Ne, bod 6.
6) Použij soubor index.php (ten v každé šabloně musí existovat, a pokud neexistujte v child-template tak v parent template uričtě ano).

Problematiku demonstruje i obrázek umístěný v kodexu. Ten obsahuje rozhodovací procesy pro všechny druhy obsahu WordPressu.

Takže již víme, že pro vytvoření speciální šablony pro jednu konkrétní rubriku nám stačí nakopírovat soubor category.php (nebo archive.php či index.php – podle toho který v naší šabloně existuje) a přejmenovat jej buď do tvaru se slugem (čili názvem v pěkné url – s pomlčkami namísto mezer a bez diakritiky) a nebo s id. No a poté již můžeme upravovat či zcela od píky vytvářet speciální zobrazení.

Úprava hlavičky, patičky a sidebaru

No, ale co když chceme upravit také hlavičku, patičku či sidebar? Na to nám slouží parametr funkcí get_header(), get_footer()get_sidebar().

Všem třem funkcím lze shodně přidat do jejich volání parametr s názvem, který poté zobrazí konkrétní soubor. Čili pokud chceme mít speciální šablonu pro hlavičku v naší template kategorie, upravíme volání funkce get_header(); v šabloně naší speciální kategorie. Třeba v souboru category-moje-kategorie.php.

<?php get_header('moje-kategorie'); ?>

Tato funkce bude hledat soubor s názvem header-moje-kategorie.php. Analogicky můžeme volat i další dvě zmíněné funkce:

get_footer('moje-kategorie'); //hledá soubor footer-moje-kategorie.php
get_sidebar('moje-kategorie'); //hledá soubor sidebar-moje-kategorie.php

Tím si můžeme zcela přizpůsobit výpis obsahu jedné konkrétní kategorie, stránky či příspěvku.

Snad jen jako poznámku pod čarou berte informaci, že pokud chceme rozdílné zobrazení homepage od kategorie či příspěvku, stačí vytvořit v šabloně soubory category.php a single.php a případně z nich volat jinou hlavičku, patičku a sidebar.

Něco jiného je když cheme vytvořit speciální šablonu pro stránku, která je volitelná z administrace. Ovšem tím jsem se již zabýval v předchozím článku.

Jak vytvořit speciální šablonu pro všechny příspěvky v jedné konkrétní kategorii rozebírám v jiném článku.