I have created a custom plugin on Wordpress that creates a custom post on installation.
The code I use is as follows:
function custom_post_type() {
$labels = array(
'name' => _x( 'Books', 'Post Type General Name', 'my-custom-domain' ),
'singular_name' => _x( 'Book', 'Post Type Singular Name', 'my-custom-domain' ),
'menu_name' => __( 'Book', 'my-custom-domain' ),
'parent_item_colon' => __( 'Parent Book', 'my-custom-domain' ),
'all_items' => __( 'All Books', 'my-custom-domain' ),
'view_item' => __( 'Show Book', 'my-custom-domain' )
);
$args = array(
'label' => __( 'Books', 'my-custom-domain' ),
'description' => __( 'Books and news', 'my-custom-domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
'taxonomies' => array( 'genres' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
'show_in_rest' => true,
);
register_post_type( 'libri', $args );
}
add_action( 'init', 'custom_post_type', 0 );
What I would like to do is to be able to create a custom field (again from code) to be inserted under this function and add it to the post created above.
A custom field such as a text field with a title and a label box in which to insert text, or a field consisting of two text boxes.
How can I create it in code and add it to the post so that when I do "Add new" I get this field to fill in?
I mean something like THIS.
There's some really great tutorials that cover this. My answer is taken from this one written by Aileen Javier from WPMU Dev
It's a 3 step process to create custom metaboxes on a page. The first step is to create the metabox using the add_meta_box() function
function libri_add_meta_box( $post ){
add_meta_box( 'libri_meta_box', 'Book Attributes', 'libri_build_meta_box', 'libri', 'side', 'low' );
}
add_action( 'add_meta_boxes_libri', 'libri_add_meta_box' );
The next step is to create a function which we use as the callback parameter in our add_meta_box (in this case 'libri_build_meta_box') - We use this to create inputs for our custom fields. In this instance a text field for Book Author.
function libri_build_meta_box( $post ){
wp_nonce_field( basename( __FILE__ ), 'libri_meta_box_nonce' );
$book_author = get_post_meta( $post->ID, '_book_author', true); ?>
<div class='inside'>
<h3>Book Author</h3>
<p>
<input type="text" name="book_author" value="<?php echo $book_author; ?>" />
</p>
</div>
<?php }
And the final step is to hook into the save_post_{$post->post_type} action, to take the request and then update the post_meta when the post is saved
function libri_save_meta_box_data( $post_id ){
if ( !isset( $_POST['food_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['food_meta_box_nonce'], basename( __FILE__ ) ) ){
return;
}
if ( isset( $_REQUEST['book_author'] ) ) {
update_post_meta( $post_id, '_book_author', sanitize_text_field( $_POST['book_author'] ) );
}
}
add_action( 'save_post_libri', 'libri_save_meta_box_data', 10, 2 );
This will create a metabox on the side of the page that has a single text input for a book author. I'd really recommend reading the whole tutorial from wpmudev, because it's really informative and helpful.
Here's the full code from my example:
<?php function libri_add_meta_box( $post ){
add_meta_box( 'libri_meta_box', 'Book Attributes', 'libri_build_meta_box', 'libri', 'side', 'low' );
}
add_action( 'add_meta_boxes_libri', 'libri_add_meta_box' );
function libri_build_meta_box( $post ){
wp_nonce_field( basename( __FILE__ ), 'libri_meta_box_nonce' );
$book_author = get_post_meta( $post->ID, '_book_author', true); ?>
<div class='inside'>
<h3>Book Author</h3>
<p>
<input type="text" name="book_author" value="<?php echo $book_author; ?>" />
</p>
</div>
<?php }
function libri_save_meta_box_data( $post_id ){
if ( !isset( $_POST['food_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['food_meta_box_nonce'], basename( __FILE__ ) ) ){
return;
}
if ( isset( $_REQUEST['book_author'] ) ) {
update_post_meta( $post_id, '_book_author', sanitize_text_field( $_POST['book_author'] ) );
}
}
add_action( 'save_post_libri', 'libri_save_meta_box_data', 10, 2 );
Related
I am stuck in a problem assigning custom capability with custom post type to a custom role.
The issue is i want to remove the Add New ( Not with a CSS hack or by unsetting menu item ) option of my custom post type. I have already come across answers that suggest many solutions but none of them works perfectly.
Closest to what i want is this :
register_post_type( 'custom_post_type_name', array(
'capability_type' => 'post',
'capabilities' => array(
'create_posts' => 'do_not_allow', // false < WP 4.5, credit #Ewout
),
'map_meta_cap' => true, // Set to `false`, if users are not allowed to edit/delete existing posts
));
This code removes the Add New link but it assigns the default post slug for capabilities.Notice line 2 of above code. If i change it to my custom post type slug, it stops working and i can't even go posts page.
One thing to keep in mind is that i am working with custom role, which has only read capability by default.
If i also assign the edit_posts capability then my objective is achieved, but then user can also access posts and comments, which i do not want.
Woocommerce is doing this. I dive into woocommerce code and add this line where it registers its products and orders.
'capabilities' => array( 'create_posts' => 'do_not_allow' ),
And everything works as i want. I have explored woocommerce code all day but can't find how it is doing this. Can someone else help me out on this with another pair of eyes ? :)
Much appreciated. Thanks..
I already mention to you that give us little more details about the plan that you want to do?
Here is the solution that I think it would be helpful for you.
If you want to used map_meta_cap => true then you will need to change capability_type as well with your own type, see more https://codex.wordpress.org/Function_Reference/register_post_type#capability_type
But if you set your own capability_type value then you will need to add capability to users role those you want to add.
here is a complete example.
if ( !class_exists( 'WPSE64458_CPT_Register' ) ) {
class WPSE64458_CPT_Register {
function __construct() {
add_action( 'init', array( $this, 'wpse64458_register_post_types' ), 5 );
add_action( 'admin_init', array( $this, 'wpse64458_add_caps' ), 5 );
add_filter( 'register_post_type_args', array( $this, 'wpse64458_modify_cpt_registry' ) , 10, 2 );
}
/**
* Register core post types.
*/
public function wpse64458_register_post_types() {
if ( ! is_blog_installed() || post_type_exists( 'member' ) ) {
return;
}
register_post_type( 'member',
apply_filters( 'wpse64458_callb_post_type_member',
array(
'labels' => array(
'name' => __( 'Members', 'domaintext' ),
'singular_name' => __( 'Member', 'domaintext' ),
'all_items' => __( 'All Members', 'domaintext' ),
'menu_name' => _x( 'Members', 'Admin menu name', 'domaintext' ),
'add_new' => __( 'Add New', 'domaintext' ),
'add_new_item' => __( 'Add new member', 'domaintext' ),
'edit' => __( 'Edit', 'domaintext' ),
'edit_item' => __( 'Edit member', 'domaintext' ),
'new_item' => __( 'New member', 'domaintext' ),
'view' => __( 'View member', 'domaintext' ),
'view_item' => __( 'View member', 'domaintext' ),
'search_items' => __( 'Search members', 'domaintext' ),
'not_found' => __( 'No members found', 'domaintext' ),
'not_found_in_trash' => __( 'No members found in trash', 'domaintext' ),
'parent' => __( 'Parent member', 'domaintext' ),
'featured_image' => __( 'Member image', 'domaintext' ),
'set_featured_image' => __( 'Set member image', 'domaintext' ),
'remove_featured_image' => __( 'Remove member image', 'domaintext' ),
'use_featured_image' => __( 'Use as member image', 'domaintext' ),
'insert_into_item' => __( 'Insert into member', 'domaintext' ),
'uploaded_to_this_item' => __( 'Uploaded to this member', 'domaintext' ),
'filter_items_list' => __( 'Filter members', 'domaintext' ),
'items_list_navigation' => __( 'Members navigation', 'domaintext' ),
'items_list' => __( 'Members list', 'domaintext' ),
),
'public' => true,
'show_ui' => true,
'capability_type' => 'member',
'map_meta_cap' => true,
'menu_icon' => 'dashicons-groups',
'publicly_queryable' => true,
'exclude_from_search' => false,
'hierarchical' => false, // Hierarchical causes memory issues - WP loads all records!
'rewrite' => array( 'slug' => 'member' ),
'query_var' => true,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
'has_archive' => 'members',
'show_in_nav_menus' => true,
'show_in_rest' => true,
)
)
);
} // end of wpse64458_register_post_types
/**
* Get capabilities.
*
* #return array
*/
private function wpse64458_set_caps() {
$capabilities = array();
$capability_types = array( 'member' );
foreach ( $capability_types as $capability_type ) {
$capabilities[ $capability_type ] = array(
// Post type
"edit_{$capability_type}",
"read_{$capability_type}",
"delete_{$capability_type}",
"edit_{$capability_type}s",
"edit_others_{$capability_type}s",
"publish_{$capability_type}s",
"read_private_{$capability_type}s",
"delete_{$capability_type}s",
"delete_private_{$capability_type}s",
"delete_published_{$capability_type}s",
"delete_others_{$capability_type}s",
"edit_private_{$capability_type}s",
"edit_published_{$capability_type}s",
// Terms
// "manage_{$capability_type}_terms",
// "edit_{$capability_type}_terms",
// "delete_{$capability_type}_terms",
// "assign_{$capability_type}_terms",
);
}
return $capabilities;
}
/*
Add Capability
*/
public function wpse64458_add_caps(){
global $wp_roles;
if ( ! class_exists( 'WP_Roles' ) ) {
return;
}
if ( ! isset( $wp_roles ) ) {
$wp_roles = new WP_Roles();
}
$capabilities = $this->wpse64458_set_caps();
foreach ( $capabilities as $cap_group ) {
foreach ( $cap_group as $cap ) {
$wp_roles->add_cap( 'editor', $cap );
$wp_roles->add_cap( 'administrator', $cap );
}
}
}
public function wpse64458_modify_cpt_registry( $args, $post_type ){
// Do not filter any other post type
if ( 'member' !== $post_type ) {
// Give other post_types their original arguments
return $args;
}
if( current_user_can('editor') ) {
$args['capabilities']['create_posts'] = false;
}
// Give the custom-css-js post type it's arguments
return $args;
}
}
}
then inherite the class with new WPSE64458_CPT_Register();
With this example I disable editor role to add new member post functionality. modify whatever you like, or you can do this others as well. but you previously mention that you already tried to follow WooCommerce, actually they also do this way,
Hope it make sense to you.
HappyCodding!
You can restrict specific user role to custom post by below script :
Add custom Role
add_action('init','add_my_custom_role');
function add_my_custom_role() {
add_role('my_custom_role',
'Custom Role',
array(
'read' => true,
'edit_posts' => false,
'delete_posts' => false,
'publish_posts' => false,
'upload_files' => false,
'publish_posts' => false,
'create_posts' => false,
)
);
}
Register Custom post
add_action( 'init', 'my_custom_post_type');
function my_custom_post_type() {
$args = array(
'label' => __( 'Custom post', 'custom-text-domain' ),
'description' => __( 'Custom post', 'custom-text-domain' ),
'labels' => $labels,
'supports' => array( 'title', 'comments', 'revisions', ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'rewrite' => $rewrite,
'capability_type' => array('custom_post','custom_post'),
'map_meta_cap' => true, // Set to `false`, if users are not allowed to edit/delete existing posts
);
register_post_type( 'custom_post', $args );
}
Allow user capabilities for post on the basis of roles
add_action('admin_init','custom_post_add_role_caps',999);
function custom_post_add_role_caps() {
// Add the roles you'd like to administer the custom post types
$roles = array('my_custom_role','editor');
// Loop through each role and assign capabilities
foreach($roles as $the_role) {
$role = get_role($the_role);
$role->add_cap( 'read' );
$role->add_cap( 'read_custom_post');
$role->add_cap( 'read_private_custom_post' );
$role->add_cap( 'edit_custom_post' );
$role->add_cap( 'edit_custom_post' );
$role->add_cap( 'edit_others_custom_post' );
$role->add_cap( 'edit_published_custom_post' );
$role->add_cap( 'publish_custom_post' );
$role->add_cap( 'delete_others_custom_post' );
$role->add_cap( 'delete_private_custom_post' );
$role->add_cap( 'delete_published_custom_post' );
}
}
I hope this will help you, to get more help please visit
https://codex.wordpress.org/Function_Reference/register_post_type
and
https://codex.wordpress.org/Roles_and_Capabilities
This is my first time i use wordpress for create apps. in there i want to make an api but dont know how to make it in wordpress.
this my code in website :
function drivers_post_type() {
$labels = array(
'name' => _x( 'driver', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'driver', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'driver', 'text_domain' ),
'name_admin_bar' => __( 'Post Type', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'search_items' => __( 'Search Item', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
);
$args = array(
'label' => __( 'driver', 'text_domain' ),
'description' => __( 'driver', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title','thumbnail' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'rewrite' => array('slug' => 'driver'),
'capability_type' => 'page',
);
register_post_type( 'drivers', $args );
}
// Hook into the 'init' action
add_action( 'init', 'drivers_post_type', 0 );
// Little function to return a custom field value
function driverMB_get_custom_field( $value ) {
global $post;
$custom_field = get_post_meta( $post->ID, $value, true );
if ( !empty( $custom_field ) )
return is_array( $custom_field ) ? stripslashes_deep( $custom_field ) : stripslashes( wp_kses_decode_entities( $custom_field ) );
return false;
}
// Register the Metabox
function driverMB_add_custom_meta_box() {
add_meta_box(
'driverMB-meta-box',
__( 'driver Info', 'textdomain' ),
'driverMB_meta_box_output',
'drivers',
'normal',
'default'
);
}
add_action( 'add_meta_boxes', 'driverMB_add_custom_meta_box' );
// Output the Metabox
function driverMB_meta_box_output( $post ) {
// create a nonce field
wp_nonce_field( 'my_driverMB_meta_box_nonce', 'driverMB_meta_box_nonce' ); ?>
<p>
<label><b>ID</b></label>
<label><?php echo get_the_ID() ?></label>
</p>
<p>
<label><b>Username</b></label>
<input type="text" placeholder="Username" name="username" id="username" value="<?php echo driverMB_get_custom_field( 'username' ); ?>" style="width:100%;" />
</p>
<p>
<label><b>Password</b></label>
<input type="password" placeholder="Password" name="password" id="password" value="<?php echo driverMB_get_custom_field( 'password' ); ?>" style="width:100%;" />
</p>
<p>
<label><b>Email</b></label>
<input type="text" placeholder="Email" name="email" id="email" value="<?php echo driverMB_get_custom_field( 'email' ); ?>" style="width:100%;" />
</p>
<p>
<label><b>Phone Number</b></label>
<input type="text" placeholder="Ext : 088216192560" name="phone" id="phone" value="<?php echo driverMB_get_custom_field( 'phone' ); ?>" style="width:100%;" />
</p>
<?php
}
// Save the Metabox values
function driverMB_meta_box_save( $post_id ) {
// Stop the script when doing autosave
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// Verify the nonce. If insn't there, stop the script
if( !isset( $_POST['driverMB_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['driverMB_meta_box_nonce'], 'my_driverMB_meta_box_nonce' ) ) return;
// Stop the script if the user does not have edit permissions
if( !current_user_can( 'edit_post' ) ) return;
// Save the textfield
if( isset( $_POST['username'] ) )
update_post_meta( $post_id, 'username', esc_attr( $_POST['username'] ) );
if( isset( $_POST['password'] ) )
update_post_meta( $post_id, 'password', esc_attr( $_POST['password'] ) );
if( isset( $_POST['email'] ) )
update_post_meta( $post_id, 'email', esc_attr( $_POST['email'] ) );
if( isset( $_POST['phone'] ) )
update_post_meta( $post_id, 'phone', esc_attr( $_POST['phone'] ) );
}
add_action( 'save_post', 'driverMB_meta_box_save' );
i dont know how to create it as api. my friend told me to create if url equals then perform action function, but i dont know how ?
Does someone tell me or help me to create an api for wordpress ?
No doubt there are many other plugins in the market too but these are the two which I used personally for creating APIs in WordPress:
Using WP Rest API (Now a days it is officially supported by WordPress):
The detailed documentation for the same is provided here.
Using Json API plugin (for simplicity). If you use this plugin then it will allow you to create your "Controller", "Model" etc files and hence you can write your custom endpoints. You can check more details here.
Note : I have used this plugin last year and it works great.
To answer your question, I must say:
You must first create a folder in the mainstream WordPress path and place your project files in it.
enter image description here
Then add your original file with extension .php Put it in it.
Note that you need to move your code based on the function.
How can I create attributes for WooCommerce from a plugin?
I find only :
wp_set_object_terms( $object_id, $terms, $taxonomy, $append);
From this stack-question
But this approach required id of some product. I need to generate some attributes not attached to any products.
To create a term you can use wp_insert_term()
like so:
wp_insert_term( 'red', 'pa_colors' );
where colors is the name of your attribute. The taxonomy name of an attribute is always prepended by pa_.
Edit Attributes are merely custom taxonomies. Or you could say they are dynamic taxonomies that are manually created by the user in the back-end. Still, all the same, custom taxonomy rules apply.
You can see the source code here which loops through the attributes and runs register_taxonomy() on each. So to create a new attribute (remember it is just a taxonomy) then you need to run register_taxonomy() and simple prepend pa_ to the start of the taxonomy name.
Mimicking some of the values of the taxonomy args from core would get you something like this for a 'Colors' attribute.
/**
* Register a taxonomy.
*/
function so_29549525_register_attribute() {
$permalinks = get_option( 'woocommerce_permalinks' );
$taxonomy_data = array(
'hierarchical' => true,
'update_count_callback' => '_update_post_term_count',
'labels' => array(
'name' => __( 'My Colors', 'your-textdomain' ),
'singular_name' => __( 'Color', 'your-textdomain' ),
'search_items' => __( 'Search colors', 'your-textdomain' ),
'all_items' => __( 'All colors', 'your-textdomain' ),
'parent_item' => __( 'Parent color', 'your-textdomain' ),
'parent_item_colon' => __( 'Parent color:', 'your-textdomain' ),
'edit_item' => __( 'Edit color', 'your-textdomain' ),
'update_item' => __( 'Update color', 'your-textdomain' ),
'add_new_item' => __( 'Add new color', 'your-textdomain' ),
'new_item_name' => __( 'New color', 'your-textdomain' )
),
'show_ui' => false,
'query_var' => true,
'rewrite' => array(
'slug' => empty( $permalinks['attribute_base'] ) ? '' : trailingslashit( $permalinks['attribute_base'] ) . sanitize_title( 'colors' ),
'with_front' => false,
'hierarchical' => true
),
'sort' => false,
'public' => true,
'show_in_nav_menus' => false,
'capabilities' => array(
'manage_terms' => 'manage_product_terms',
'edit_terms' => 'edit_product_terms',
'delete_terms' => 'delete_product_terms',
'assign_terms' => 'assign_product_terms',
)
);
register_taxonomy( 'pa_my_color', array('product'), $taxonomy_data );
}
add_action( 'woocommerce_after_register_taxonomy', 'so_29549525_register_attribute' );
Update 2020-11-18
Attribute taxonomies are stored in the {$wpdb->prefix}woocommerce_attribute_taxonomies database table. And from there WooCommerce runs register_taxonomy() on each one that's found in the table. So in order to create an attribute taxonomy, a row should be added to this table. WooCommerce has a function wc_create_attribute() that will handle this for us. (Since 3.2+).
My conditional logic to test if the attribute exists is not the greatest and I would advise using some kind of version option in your plugin's update routine. But as an example of using wc_create_taxonomy() this should insert an attribute called "My Color".
/**
* Register an attribute taxonomy.
*/
function so_29549525_create_attribute_taxonomies() {
$attributes = wc_get_attribute_taxonomies();
$slugs = wp_list_pluck( $attributes, 'attribute_name' );
if ( ! in_array( 'my_color', $slugs ) ) {
$args = array(
'slug' => 'my_color',
'name' => __( 'My Color', 'your-textdomain' ),
'type' => 'select',
'orderby' => 'menu_order',
'has_archives' => false,
);
$result = wc_create_attribute( $args );
}
}
add_action( 'admin_init', 'so_29549525_create_attribute_taxonomies' );
For Woocommerce 3+ (2018)
To create a new product attribute from a label name use the following function:
function create_product_attribute( $label_name ){
global $wpdb;
$slug = sanitize_title( $label_name );
if ( strlen( $slug ) >= 28 ) {
return new WP_Error( 'invalid_product_attribute_slug_too_long', sprintf( __( 'Name "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
} elseif ( wc_check_if_attribute_name_is_reserved( $slug ) ) {
return new WP_Error( 'invalid_product_attribute_slug_reserved_name', sprintf( __( 'Name "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
} elseif ( taxonomy_exists( wc_attribute_taxonomy_name( $label_name ) ) ) {
return new WP_Error( 'invalid_product_attribute_slug_already_exists', sprintf( __( 'Name "%s" is already in use. Change it, please.', 'woocommerce' ), $label_name ), array( 'status' => 400 ) );
}
$data = array(
'attribute_label' => $label_name,
'attribute_name' => $slug,
'attribute_type' => 'select',
'attribute_orderby' => 'menu_order',
'attribute_public' => 0, // Enable archives ==> true (or 1)
);
$results = $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $data );
if ( is_wp_error( $results ) ) {
return new WP_Error( 'cannot_create_attribute', $results->get_error_message(), array( 'status' => 400 ) );
}
$id = $wpdb->insert_id;
do_action('woocommerce_attribute_added', $id, $data);
wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );
delete_transient('wc_attribute_taxonomies');
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Based on:
Product Attribute wc_create_attribute() function code (Woocommerce 3.2+).
Create programmatically a variable product and two new attributes in Woocommerce
Related: Create programmatically a product using CRUD methods in Woocommerce 3
I have a custom post type and custom taxonomy set up using the code below in functions.php.
The URL writes correctly when clicking through on the archive pages on the front end and when clicking "View Post" in the admin edit screen. But when the post is returned in site search results, the custom taxonomy is literally missing. The URL on search results is http://www.example.com/foo//postname.
Any idea why the custom taxonomy in the URL would work in some situations but not in others?
add_action( 'init', 'create_foo_posttype' );
function create_foo_posttype() {
$tax_labels = array(
'name' => _x( 'Foo Categories', 'taxonomy general name' ),
'singular_name' => _x( 'Foo Category', 'taxonomy singular name' ),
'all_items' => __( 'All Foo Categories' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Foo Category' ),
'update_item' => __( 'Update Foo Category' ),
'add_new_item' => __( 'Add New Foo Category' ),
'new_item_name' => __( 'New Foo Category Name' ),
);
register_taxonomy('foo_categories','foo',array(
'labels' => $tax_labels,
'hierarchical' => true,
'has_archive' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'foo' )
));
register_post_type( 'foo',
array(
'labels' => array(
'name' => __( 'Foo' ),
'singular_name' => __( 'Foo' )
),
'public' => true,
'exclude_from_search' => false,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 100,
'capability_type' => 'post',
'supports' => array( 'title', 'author', 'thumbnail', 'trackbacks', 'revisions' ),
'taxonomies' => array( 'foo_categories' ),
'has_archive' => true,
'rewrite' => array( 'slug' => 'foo/%foo_categories%')
)
);
flush_rewrite_rules();
}
add_action( 'init', 'cust_rewrite_init' );
function cust_rewrite_init() {
$GLOBALS['wp_rewrite']->use_verbose_page_rules = true;
}
add_filter( 'page_rewrite_rules', 'cust_rewrite_collect_page_rewrite_rules' );
function cust_rewrite_collect_page_rewrite_rules( $page_rewrite_rules )
{
$GLOBALS['cust_rewrite_page_rewrite_rules'] = $page_rewrite_rules;
return array();
}
add_filter( 'rewrite_rules_array', 'cust_rewrite_prepend_page_rewrite_rules' );
function cust_rewrite_prepend_page_rewrite_rules( $rewrite_rules )
{
return $GLOBALS['cust_rewrite_page_rewrite_rules'] + $rewrite_rules;
}
I found the problem. It wasn't in the code I posted originally. It was here:
add_filter('post_type_link', 'cust_permalink_structure', 1, 4);
function cust_permalink_structure($post_link, $post, $leavename, $sample)
{
if ( false !== strpos( $post_link, '%foo_categories%' ) ) {
$post_type_term = get_the_terms( $post->ID, 'foo_categories' );
$post_link = str_replace( '%foo_categories%', $post_type_term[0]->slug, $post_link );
}
return $post_link;
}
Using $post_type_term[0]->slug; worked if a post had more than one tax value, but failed when the post had only one (which all of my posts do). To fix it, I used array_pop instead of the other array call and it works fine. The resolved code:
add_filter('post_type_link', 'cust_permalink_structure', 1, 4);
function cust_permalink_structure($post_link, $post, $leavename, $sample)
{
if ( false !== strpos( $post_link, '%foo_categories%' ) ) {
$post_type_term = get_the_terms( $post->ID, 'foo_categories' );
$one_term = array_pop($post_type_term);
$post_link = str_replace( '%foo_categories%', $one_term->slug, $post_link );
}
return $post_link;
}
I just need the extra fields on my post but without using advance custom fields.
Please what should i do the changes in my function.php
i have simple do the below code for custom post i need on extra field which name should be "company" what changes i required in below code.
please can anyone tell me ?
add_action( 'init', 'client' );
function client() {
register_post_type( 'client',
array(
'labels' => array(
'name' => __( 'Our Client' ),
'singular_name' => __( 'client' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'client'),
'supports' => array( 'title','thumbnail')
)
);
}
Try the following code:
add_action( 'init', 'client' );
function client() {
register_post_type( 'client',
array(
'labels' => array(
'name' => __( 'Our Client' ),
'singular_name' => __( 'client' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'client'),
'supports' => array( 'title','thumbnail'),
'register_meta_box_cb' => 'add_client_metaboxes',
)
);
}
//Code for meta box.
add_action( 'add_meta_boxes', 'add_client_metaboxes' );
function add_client_metaboxes() {
add_meta_box('company_description', 'Company', 'company_description', 'client');
}
function company_description() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="itemmeta_noncename" id="itemmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the location data if its already been entered
$comapny_detail = get_post_meta($post->ID, 'comapny_detail', true);
// Echo out the field
echo '<input type="text" name="comapny_detail" value="'.$comapny_detail.'">';
}
Edited:
function wpt_client() {
register_post_type( 'client',
array(
'labels' => array(
'name' => __( 'Clients' ),
'singular_name' => __( 'Client' ),
'add_new' => __( 'Add New Client' ),
'add_new_item' => __( 'Add New Client' ),
'edit_item' => __( 'Edit Client' ),
'new_item' => __( 'Add New Client' ),
'view_item' => __( 'View Client' ),
'search_items' => __( 'Search Client' ),
'not_found' => __( 'No cleint found' ),
'not_found_in_trash' => __( 'No client found in trash' )
),
'public' => true,
'supports' => array( 'title','editor','thumbnail'),
'capability_type' => 'post',
'rewrite' => array("slug" => "client"), // Permalinks format
'menu_position' => 20,
'register_meta_box_cb' => 'create_meta_boxes',
)
);
}
add_action( 'init', 'wpt_client' );
/* Custom meta boxes */
add_action( 'add_meta_boxes', 'create_meta_boxes' );
function create_meta_boxes() {
add_meta_box( 'my-meta-box-id', __('Company Name'), 'client_info', 'client', 'normal', 'low' );
}
// Create meta box: Company Name
function client_info( $post ) {
$values = get_post_custom( $post->ID );
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<?php $text = get_post_meta($post->ID, 'client_info', true); ?>
<input type="text" name="client_info" id="client_info" style="width: 100%; margin: 6px 0;" value="<?php echo $text; ?>" />
<?php
}
// Save meta box: Company Name
add_action( 'save_post', 'save_client_info' );
function save_client_info( $post_id ) {
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
if( !current_user_can( 'edit_post' ) ) return;
$allowed = array(
'a' => array( // on allow a tags
'href' => array() // and those anchords can only have href attribute
)
);
if( isset( $_POST['client_info'] ) )
update_post_meta( $post_id, 'client_info', wp_kses( $_POST['client_info'], $allowed ) );
}