Archive for category Custom Post Types

How to Hide Add New Buttons For a WordPress Specific Custom Post Type on Wp-Admin

Sometimes, when you register a custom post type, you may want to hide “add new” buttons on wp-admin menu and edit page, to keep a fixed number of posts to be managed by the user without changing the original website concept or design.

Just paste the code bellow on your theme functions.php file, and the “add new” buttons will be hidden from wp-admin users.

// hide "add new" on wp-admin menu
function hd_add_box() {
  global $submenu;
  unset($submenu['edit.php?post_type=yourcustomposttype'][10]);
}

// hide "add new" button on edit page
function hd_add_buttons() {
  global $pagenow;
  if(is_admin()){
	if($pagenow == 'edit.php' && $_GET['post_type'] == 'yourcustomposttype'){
		echo ".add-new-h2{display: none;}";
	}  
  }
}
add_action('admin_menu', 'hd_add_box');
add_action('admin_head','hd_add_buttons');

Leave a comment

Quick solution to display a menu like list of WordPress Custom Post Type Posts(with Custom Taxonomy) in case of emergency

Well, I was in a hurry, the customer needed to have his site working as soon as possible, and I had to display a menu like list of WordPress Custom Post Types working for three different languages, but I didn’t have time to think of a elegant way to make it work. So I’ve created this little hack, that checks the custom taxonomy for each post and uses a conditional to decide what happens as a quick solution, and I’m sharing with you, to use in a case of emergency 🙂
Bem, eu estava com pressa, o cliente precisava ter seu dite funcionando o mais rĂĄpido possĂ­vel, e eu tinha que exibir uma lista tipo menu de Tipos de Posts Customizados WordPress funcionando para trĂȘs diferentes idiomas, mas eu nĂŁo tinha tempo para pensar em um jeito elegante de fazer funcionar. EntĂŁo criei este pequeno hack que verifica a taxonomia customizada para cada post e decide o que acontece usando uma condicional como uma solução rĂĄpida, e estou compartilhando com vocĂȘs, para usarem em caso de emergĂȘncia 🙂

<ul class="submenu">
   <?
   // here it's the query for my custom post type - Movies 
   $querycp = array( 'post_type'=>'Movies','posts_per_page' => -1 );
   query_posts($querycp);
   while (have_posts()) : the_post();
   // here we check what's the post custom taxonomy, if it is the language we need
   $terms = get_the_terms(get_the_ID(), 'movies_cat');
    foreach ( $terms as $term ) {
        $catref = $term->slug;
    }
   //
     if($catref=="english"):
     ?>
      <li><a href="<?=get_permalink()?>" title=""><?=get_the_title()?></a></li>
     <?
     endif;
   endwhile;
    ?>
</ul>

,

2 Comments

WordPress Custom Taxonomy Page Example with Taxonomy Selection Function(select field)

Today I’ll show something quite useful. With just four steps, we will build a custom taxonomy page, that uses a function to build a select field(<select>), that reloads the custom taxonomy page retrieving posts based on the selected option(the selected taxonomy for a specific custom post type).
Hoje vou mostrar algo bastante Ăștil. Com apenas quatro passos, vamos construir uma pĂĄgina de taxonomia customizada, que usa uma função para construir um campo select(<select>), que recarrega a pĂĄgina recuperando posts baseados na opção selecionada(a taxonomia selecionada para um tipo de post customizado).

Step One:

First of all, we need to register a custom post type called video and a custom taxonomy called genre, as I show on my previous post.
Antes de mais nada, precisamos registrar um tipo de post customizado chamado video e uma taxonomia customizada chamada genre, como mostro em meu post anterior.

Step Two:

The function bellow builds a <select> field with options based on taxonomies registered for a specific custom post type. The code also brings a javascript function that redirects to the taxonomy page(taxonomy-genre.php on this example), where you can show the posts from a specific custom taxonomy. Put it on your functions.php file, on your theme directory.
A função abaixo constrĂłi um campo <select> com opçÔes baseadas em taxonomias registradas para um tipo de post customizado especĂ­fico. O cĂłdigo tambĂ©m trĂĄs uma função javascript que redireciona Ă  pĂĄgina da taxonomia(taxonomy-genre.php neste exemplo), onde vocĂȘ pode mostrar os posts de uma taxonomia customizada especĂ­fica. Coloque ele no seu arquivo functions.php, no diretĂłrio de seu tema.

<?
function wp_selcstch_taxonomies( $args = '' ) {
	
	$defaults = array(			
		'taxonomy' 	=> 'category',		
  		'seltitle'	=> '',
		'selnamen'	=> '',
		'selidcss'	=> '' ,
		'baselink'	=> '', 
		'echo' => 1,
		'hide_empty'   => 0
	);

	$r = wp_parse_args( $args, $defaults );
	extract( $r );

	if ( !taxonomy_exists($taxonomy) )
		return false;
	
	if( isset( $r['seltitle']) && $r['seltitle']!=""):$idtlt =  $r['seltitle'];else:$idtlt =  '';endif;		
	if( isset( $r['selnamen']) && $r['selnamen']!=""):$idnam =  " name='".$r['selnamen']."' ";else:$idnam = '';endif;
	if( isset( $r['selidcss']) && $r['selidcss']!=""):$idcss =  " id='".$r['selidcss']."' ";else:$idcss = '';endif;	

	$categories = get_categories( $r );
	$swlink = false;
	$swchan = '';
	$output = '';

	// javascript function to redirect(reload) the page
	if( isset( $r['baselink']) && $r['baselink']!=""):
		$output .= '<script language="javascript">';
		$output .= 'function fgotxm(obj){';
		$output .= 'if(obj.options[obj.options.selectedIndex].value!=""){';
		$output .= 'window.location.href=obj.options[obj.options.selectedIndex].value;';
		$output .= '}';
		$output .= '}';
		$output .= '</script>';
		$swlink = true;
		$swchan = " onchange='fgotxm(this)'";
	endif;

	// html begin
	$output .= "<select".$idnam.$idcss.$swchan.">";
	if($idtlt!=""){
	$output .= "<option value=''>".$idtlt."</option>";;	
	}
	foreach ($categories as $cat):
		if($cat->category_nicename!=$taxonomy){
			if($swlink):$golnk =  " value='".$r['baselink']."/".$cat->slug."' ";else:$golnk = '';endif;
			$output .= "<option".$golnk.">".$cat->name."</option>";
		}
	endforeach;
	$output .= "</select>";
	
	if ( $echo )
		echo $output;
	else
		return $output;
}
?>

Step Three:

Now, let’s build a taxonomy page, called taxonomy-genre.php and save it on the theme directory.
Agora vamos construir uma pĂĄgina de taxonomia, chamada taxonomy-genre.php e salvĂĄ-la no diretĂłrio de seu tema.

<? 
// Let's get the term that was called by the url
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

// here we will pass some parameters for our function that builds the select
$taxonomy   = 'genre'; // the taxonomy slug
$seltitle	= 'Select a Option'; // the select title
$selnamen	= 'select_opt'; // the select name
$selidcss	= ''; // a css id for the select, if wanted
$baselink	= get_bloginfo('url') . "/".'genre'; // and our page base link
// the baselink is the workaround we use to make WordPress find the taxonomy page

$args = array(
  'taxonomy'     => $taxonomy ,
  'seltitle'	 => $seltitle ,
  'selnamen'	 => $selnamen ,
  'selidcss'	 => $selidcss,
  'baselink'	 => $baselink,
  'echo'	 => 0
);

// here we call the function that builds the select
$combotax = wp_selcstch_taxonomies( $args) ;

// and here we set two conditions based on the term asked on the url to build the query
//
// first we call all the genres(genre taxonomy) for the video custom post type 
// it will be used when the user calls http://yourdomain/genre/all/ on your browser 
if($term->slug=="all"){ 
	$querycp = array( 'post_type'=>'video','posts_per_page' => -1 );
}
// then we call a specific genre(genre taxonomy) for the video custom post type e.g. scifi 
// it will be used when the user calls http://yourdomain/genre/scifi/ on your browser 
else{
	$querycp = array( 'post_type'=>'video', 'genre' => $term->slug, 'posts_per_page' => -1 );	
}
?>
<html>
<body>
<head>
<title>Example</title>
</head>

<?=$combotax."<br>"; // let's display the combo ?>

<? 
// and build the loop
query_posts($querycp);
if (have_posts()) :
  while (have_posts()) : the_post();								  
    echo get_the_title()."<br>";
    echo get_the_content()."<br>";
  endwhile;
endif;
?>
</body>
</html>

Step Four:

Now you must go to wp-admin. On Videos menu, choose Genres and create a main genre called “all”, with slug “all”. Then you can add some child genres, something like “drama” with slug “drama”, “scifi” with slug “scifi”, etc(take a look on the picture).

Genres for videos

Click to open - genres for custom post type video


Agora vocĂȘ deve ir atĂ© o wp-admin. No menu Videos, escolha Genres e crie um genĂȘro principal chamado “all”, com slug “all”. EntĂŁo vocĂȘ pode adicionar alguns genĂȘros filhos, algo como “drama” com slug “drama”, “scifi” com slug “scifi”, etc(dĂȘ uma olhada na figura).

Don’t forget to add some posts to each child genre to display on your custom taxonomy page. Last but not least, a important tip: after registering a custom taxonomy, go to wp-admin and simply visit the permalinks settings page. It flushes all WordPress permalink rules, so it will make your changes related to the taxonomy page work.
NĂŁo esqueça de adicionar alguns post para cada genĂȘro filho para mostrar em sua pĂĄgina de taxonomia customizada. Por Ășltimo, mas importante, uma dica: depois de registrar uma taxonomia customizada, vĂĄ atĂ© o wp-admin e simplesmente visite a pĂĄgina de configuraçÔes de permalinks. Isso faz com que suas regras de permalink sejam zeradas, fazendo suas mudanças relacionadas Ă  pĂĄgina de taxonomia funcionar.

Hope you find this example useful.
Espero que vocĂȘ ache este exemplo Ăștil.

,

Leave a comment

Retrieving The Total Number of Posts from a Specific Custom Post Type WordPress Taxonomy

The function bellow can be used to retrieve the total number of posts from a specific custom post type taxonomy in WordPress sites. There are only two steps, supposing you’ve registered a custom post type video and a taxonomy genre as I show on a previous post.
A função abaixo pode ser usada para retornar o nĂșmero total de posts de uma taxonomia especĂ­fica de um tipo de post customizado. SĂŁo apenas dois passos, supondo que vocĂȘ criou um tipo de post customizado ‘video’ e uma taxonomia ‘genre’ como eu mostro em um post anterior.

Step 1:

<?
// put this code on your functions.php file, on your theme directory
// the function use the custom post type registration and the taxonomy slug as parameters
function wt_get_custom_taxonomy_count($ptype,$pterm) {
	global $wpdb;
	$SQL  = "SELECT count(*) FROM $wpdb->posts posts, $wpdb->terms terms, $wpdb->term_relationships rels ";
	$SQL .= "WHERE posts.post_status = 'publish' ";
	$SQL .= "AND post_type = '".$ptype."' ";
	$SQL .= "AND posts.ID = rels.object_id ";
	if($pterm!=""):
	$SQL .= "AND terms.slug = '".$pterm."' ";
	endif;
	$SQL .= "AND terms.term_id = rels.term_taxonomy_id";
	return $wpdb->get_var($SQL);
}
?>

Step 2:

<?
// put this on the theme page where you want the info to show
echo wt_get_custom_taxonomy_count('video','genre');
?>

This code can be very useful to be used when you are working on a WordPress custom taxonomy page.
Este cĂłdigo pode ser bastante Ăștil quando vocĂȘ estĂĄ trabalhando em uma pĂĄgina de taxonomia customizada do WordPress.

,

Leave a comment

WordPress Custom Taxonomy Page Example – Displaying Custom Post Types Posts

There is a little explanation before going to the code, you can read it or go straight to the code, copy it, paste it and make it work.
HĂĄ uma pequena explicação antes de ir ao cĂłdigo, vocĂȘ pode ler ou ir direto ao cĂłdigo, copiar, colar e fazer funcionar.

First of all, you’d better take a look on my two previous posts, about registering custom post types and displaying basic info from a custom taxonomy.
It will help you to understand where we are going.

Antes de mais nada, Ă© melhor vocĂȘ dar uma olhada em meus dois posts anteriores, sobre registrar tipos de posts customizados e exibir informação bĂĄsica de uma taxonomia customizada.
Isso vai te ajudar a compreender aonde estamos indo.

After a custom post type called ‘videos’ and a taxonomy called ‘genre’ are registered, and some posts are associated with the ‘scifi’ term on wp-admin, we will use the taxonomy.php page, on the theme directory, to retrieve content from the custom post type. So it’s good understand the WordPress template hierarchy.
Depois que um tipo de post customizado chamado ‘videos’ e uma taxonomia chamada ‘genre’ sĂŁo registrados, e alguns posts sĂŁo associados com o termo ‘scifi’ no wp-admin, nĂłs vamos usar a pĂĄgina taxonomy.php, no diretĂłrio do tema, para retornar conteĂșdo do tipo de post customizado. EntĂŁo Ă© bom entender a hierarquia de templates WordPress.

Note that genre works like a “category menu” on wp-admin and scifiworks like a “specific category”.
Note que genre funciona como um “menu de categorias” no wp-admin e scifi funciona como uma “categoria especĂ­fica”.

When you ask for a url like http://yoursite.com/genre/scifi on your browser, WordPress will search your theme directory for three files: “taxonomy-taxonomy-term.php”, “taxonomy-taxonomy.php” and “taxonomy.php” or, in our case, “taxonomy-genre-scifi.php”, “taxonomy-scifi.php” and “taxonomy.php”.

Quando vocĂȘ chama uma url como http://yoursite.com/genre/scifi no seu navegador, o WordPress vai procurar no seu diretĂłrio de temas trĂȘs arquivos: “taxonomy-taxonomy-term.php”, “taxonomy-taxonomy.php” and “taxonomy.php” ou, no nosso caso, “taxonomy-genre-scifi.php”, “taxonomy-scifi.php” and “taxonomy.php”.

The code for the “taxonomy.php” page to display the “scifi” posts:
O cĂłdigo para a pĂĄgina “taxonomy.php” exibir os posts “scifi” Ă©:

<?
// this line makes the page find the correct data when you call http://yourblog.com/genre/scifi on your browser
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

// here we print scifi name and description
echo $term->name;
echo $term->description;

// now let's retrieve the posts data
query_posts(array( 'post_type'=>'videos', 'genre' => $term->slug, 'posts_per_page' => -1 ));
if (have_posts()) :
  while (have_posts()) : the_post();
    $cttrm = get_the_terms( get_the_ID() , 'genre' );
    // here we print the term('category') name 
    foreach ( $cttrm as $txnam ) {
      echo $txnam->name."<br />";
    }
    echo get_the_title()."<br />";
    echo get_the_content()."<br />";
  endwhile;
endif;
?>

, ,

3 Comments

Displaying Info From a Specific Custom Taxonomy Term(Hierarchical Taxonomies) On WordPress

See also Custom Taxonomy Page Example.

I’ve written before about registering and displaying custom post types on WordPress. So you’d better check my previous post to understand what is coming next(the example bellow is based on the previous post).
Eu escrevi anteriormente sobre registrar e exibir tipos de posts customizados no WordPress. EntĂŁo Ă© melhor vocĂȘ conferir meu post anterior, para entender o que vem por aĂ­(o exemplo abaixo Ă© baseado no post anterior).

As you could see, one of the cool things about WordPress custom post types is that you can register also hierarchical taxonomies that will work as “regular” post categories for your custom post types.
Como vocĂȘ pĂŽde ver, uma das coisas legais nos tipos de posts customizados do WordPress, Ă© que vocĂȘ pode tambĂ©m registrar taxonomias hierĂĄrquicas, que vĂŁo funcionar como categorias “normais” para seus tipos de posts customizados.

Although these facilities, it took me some work to find a simple way to display some info from hierarchical taxonomies(or, let’s say custom categories), and bellow(in few lines), I’ll share the result of this work with you.
Apesar destas facilidades, me custou algum trabalho descobrir um jeito simples de exibir algumas informaçÔes das taxonomias hierĂĄrquicas, e abaixo(em poucas linhas), eu vou dividir o resultado deste trabalho com vocĂȘs.

<?
// # to retrieve an array with all info from a custom term 'scifi' 
// that "begins" to a hierarquical taxonomy called 'genre'
$term = get_term_by('slug','scifi','genre');

// the example above uses slug to retrieve the info, but you can
// use other parameters, try searching for get_term_by method on WordPress Codex

// # to display 'scifi' term description defined on wp-admin
echo $term->description . "<br>";

//# you can also display the name, slug, or even the term_id
echo $term->name . "<br>";
echo $term->slug . "<br>";
echo $term->term_id . "<br>";

//# to print the array and see all the available info
print_r($term);
?>

Hope you find it useful. As I said, it looks simple and easy, but took me some work to find. 😉
Espero que vocĂȘ ache Ăștil. Como eu disse, parece simples e fĂĄcil, mas me custou algum trabalho descobrir. 😉

For further info, visit the Codex.
Para mais informaçÔes, visite o Codex.

,

1 Comment

Registering and Displaying WordPress Custom Post Types In a Very Easy Way

This post was moved to http://www.wpworking.com/category/custom-post-types-2/


In WordPress, you can define custom post types. It means that you can have on you wp-admin menu, more menu items, besides “Posts”, “Midia”, “Links”, “Pages”, etc, and work with your new post type as you do with the default menus, categorizing, adding content, etc.
No WordPress, vocĂȘ pode definir tipos de posts personalizados. Isso significa que vocĂȘ pode ter no seu menu do wp-admin, mais itens de menu alĂ©m de “Posts”, “MĂ­dia”, “Links”, “PĂĄginas”, etc, e trabalhar com els como faz com os tipos padrĂŁo, categorizando, adicionando conteĂșdo, etc.

Let’s create a new custom post type. Open your functions.php file, on your theme directory, and paste the code bellow.
Vamos criar um novo tipo de post personalizado Abra seu arquivo functions.php, no diretĂłrio de seu tema, e cole o cĂłdigo abaixo.

// The register_post_type() function is not to be used before the 'init'.
add_action( 'init', 'videos_init' );

/* Here's how to create your customized labels */
function videos_init() {
	$labels = array(
		'name' => _x( 'Videos', 'custom post type generic name' ), // Tip: _x('') is used for localization
		'singular_name' => _x( 'Videos', 'individual custom post type name' ),
		'add_new' => _x( 'Add New', 'add' ),
		'add_new_item' => __( 'Add New Video' ),
		'edit_item' => __( 'Edit Video' ),
		'new_item' => __( 'New Video' ),
		'view_item' => __( 'View Video' ),
		'search_items' => __( 'Search Videos' ),
		'not_found' =>  __( 'No Video Found' ),
		'not_found_in_trash' => __( 'No Video Found in trash' ),
		'parent_item_colon' => ''
	);

	// Create an array for the $args
	$args = array( 'labels' => $labels, /* NOTICE: the $labels variable is used here... */
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => true,
		'capability_type' => 'post',
		'hierarchical' => false,
		'menu_position' => null,
		'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
	); 

	register_post_type( 'video', $args ); /* Register it and move on */
}

Now you got a new menu on your wp-admin, called Videos. For further info about the register_post_type() function, visit the Codex.
Agora vocĂȘ tem um novo menu no seu wp-admin, chamado Videos. Para mais informaçÔes sobre a função register_post_type(), visite o Codex.

What about creating a category and a tag for this new Videos menu? Paste the code bellow on your functions.php
Que tal criar uma categoria e uma tag para este novo menu Videos? Cole o cĂłdigo abaixo em seu arquivo functions.php

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

// create two taxonomies, genres and writers for the post type "videos"
function create_video_taxonomies() {

	// Add new taxonomy, make it hierarchical (like categories)
	$labels = array(
		'name' => _x( 'Genres', 'taxonomy general name' ),
		'singular_name' => _x( 'Genres', 'taxonomy singular name' ),
		'search_items' =>  __( 'Search Genres' ),
		'all_items' => __( 'All Genres' ),
		'parent_item' => __( 'Main Genre' ),
		'parent_item_colon' => __( 'Main Genre:' ),
		'edit_item' => __( 'Edit Genre' ),
		'update_item' => __( 'Update Genre' ),
		'add_new_item' => __( 'Add Genre' ),
		'new_item_name' => __( 'New Genre Name' ),
	); 	

	register_taxonomy( 'genre', array( 'video' ), array(
		'hierarchical' => true,
		'labels' => $labels, /* NOTICE: Here is where the $labels variable is used */
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'genre' ),
	));
	// Add new taxonomy, NOT hierarchical (like tags)
	$labels = array(
		'name' => _x( 'Actor', 'Actor Name' ),
		'singular_name' => _x( 'Actor', 'Individual Actor Name' ),
		'search_items' =>  __( 'Search Actors' ),
		'popular_items' => __( 'Popular Actors' ),
		'all_items' => __( 'All Actors' ),
		'parent_item' => null,
		'parent_item_colon' => null,
		'edit_item' => __( 'Edit Actors' ),
		'update_item' => __( 'Update Actor' ),
		'add_new_item' => __( 'Add New Actor' ),
		'new_item_name' => __( 'New Actor Name' ),
		'separate_items_with_commas' => __( 'Separate Actors With Commas' ),
		'add_or_remove_items' => __( 'Add or Remove Actors' ),
		'choose_from_most_used' => __( 'Choose From Most Used Actors' )
	);
	register_taxonomy( 'actor', 'video', array(
		'hierarchical' => false,
		'labels' => $labels, /* NOTICE: the $labels variable here */
		'show_ui' => true,
		'query_var' => true,
		'rewrite' => array( 'slug' => 'actor' ),
	));
} // End of create_video_taxonomies() function.

We’ve created two taxonomies for the custom post type video. Genre(hierarchical), works as a category. Actor(not hierarchical), works as a tag. For further info about the register_taxonomy() function, visit the Codex.
Nós criamos duas taxonomias para o tipo de post personalizado video. Genre(hierårquica), funciona como uma categoria. Actor(não hierårquica) funciona como uma tag. Para maiores informaçÔes sobre a função register_taxonomy() , visite o Codex.

So much hard working! Now let’s have fun 🙂 , let’s display the posts.
Quanta trabalheira! Agora vamos nos divertir 🙂 , vamos exibir os posts.

<?
// * if you want to work with the genre category on your query
// $wp_query = new WP_Query(array('post_type' => 'video', 'genre' => 'scifi','posts_per_page' => -1));
//
// * if you want to work with the actor tag on your query
// $wp_query = new WP_Query(array('post_type' => 'video', 'genre' => 'scifi','actor' => 'keanureaves','posts_per_page' => -1));
//
$wp_query = new WP_Query(array('post_type' => 'video', 'genre' => 'scifi','actor' => 'keanureaves','posts_per_page' => -1));
if (have_posts()) :
     while (have_posts()) : the_post();
?>
     <div>
       <h3><a href="<?the_permalink();?>"><?=get_the_title();?></a></h3>
     </div>
     <div>
       <p><?=get_the_content();?></p>
     </div>
<?
    endwhile;
else:
?>
     <div>
       <p>No registers found.</p>
     </div>
<?
endif;
?>

That’s all folks. Copy, past and make it work. The code above was tested a lot, please let me know about any issue.
Era isso pessoal. Copiem, colem e façam acontecer. O código acima foi bastante testado, por favor me mantenham informado sobre qualquer dificuldade.

,

23 Comments

%d bloggers like this: