How to add custom fields to a WordPress Plugin - php

I'm being requested by my client to add a custom field that they will be able to enter in a url. The post itself is a custom plugin custom post type, this is the code I have for this portion:
register_post_type( 'storylist',
array(
'labels' => $labels,
'public' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
'show_ui' => true,
'supports' => array('title'),
)
);
add_filter( 'rwmb_meta_boxes', 'c_register_meta_boxes' );
}
function c_register_meta_boxes( $boxes ){
$prefix = 'c_rwmb_';
$boxes[] = array(
'id' => 'view',
'title' => __('View Link', 'c_rwmb' ),
'post_types' => array('storylist'),
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => __('View URL', 'c_rwmb' ),
'id' => $prefix . 'view_url',
'type' => 'text',
'size' => 60,
'clone' => false
),
)
);
return $meta_boxes;
}
Now the problem is when I go to the post, I do not see the custom meta field even showing up, is there something that I'm missing?

The custom post type("storylist") comes from the plugin right? Then you don't need to register the custom post again. You just needs to add meta field for this post type and save its value while updating the post. Once I had a experience to enable/disable sidebar using custom field. I shared my code. Hope this will help you.
<?php
add_action('admin_init','add_metabox_post_sidebar');
add_action('save_post','save_metabox_post_sidebar');
/*
* Funtion to add a meta box to enable/disable the posts.
*/
function add_metabox_post_sidebar()
{
add_meta_box("Enable Sidebar", "Enable Sidebar", "enable_sidebar_posts", "post", "side", "high");
}
function enable_sidebar_posts(){
global $post;
$check=get_post_custom($post->ID );
$checked_value = isset( $check['post_sidebar'] ) ? esc_attr( $check['post_sidebar'][0] ) : 'no';
?>
<label for="post_sidebar">Enable Sidebar:</label>
<input type="checkbox" name="post_sidebar" id="post_sidebar" <?php if($checked_value=="yes"){echo "checked=checked"; } ?> >
<p><em>( Check to enable sidebar. )</em></p>
<?php
}
/*
* Save the Enable/Disable sidebar meta box value
*/
function save_metabox_post_sidebar($post_id)
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
$checked_value = isset( $_POST['post_sidebar'] ) ? 'yes' : 'no';
update_post_meta( $post_id, 'post_sidebar', $checked_value );
}
?>
Here I have added a custom field called 'post_sidebar' for post type "post" you can change your own and change your post type in this line add_meta_box("Enable Sidebar", "Enable Sidebar", "enable_sidebar_posts", "post", "side", "high"); from "post" to "storylist".

Just for somebody who needs to add MetaBox fields via plugin, because the question is:
How to add custom fields to a WordPress Plugin
function gffgfg_add_boxes( $meta_boxes ) {
$prefix = 'some prefix';
$meta_boxes[] = array(
//metabox array
);
return $meta_boxes;
}
add_filter( 'rwmb_meta_boxes', 'gffgfg_add_boxes', 999 ); // 999

Related

How to create a custom post type template for a custom URL with taxonomy term in it?

In my WordPress v6.0.2, I have a custom taxonomy country and a custom post_type interest.
With post_type_link filter (another working function) and with the below function, I am rewriting custom post_type URLs as https://www.example.com/country_name/interest_term:
add_filter('generate_rewrite_rules', 'country_cpt_generating_rule');
function country_cpt_generating_rule($wp_rewrite) {
$rules = array();
$terms = get_terms(array(
'taxonomy' => 'country',
'hide_empty' => false,
));
$post_type = 'interest';
foreach ($terms as $term) {
$rules[$term->slug . '/interest/([^/]*)$'] = 'index.php?interest=$matches[1]&post_type=' . $post_type . 'name=$matches[1]';
}
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
While I have single-interest.php custom post_type template to show custom content, single posts are redirecting to home page with error404 class added to the body.
A var_dump(get_queried_object()); returning null.
I have flushed permalinks and also tried checking is_singular() to template redirecting, that did not worked.
How can I have a custom page template for single-interest with above custom URL?
here is the complete solution for your requirement. Please note that you do not have to regenerate new rewrite rules to be able to work with custom post-type URLs. instead, I have used filters to modify URLs based on your need. Let me know if this solves your issue. Please do not forget to flush your permalinks. There might be some edge cases that I did not put my focus on because mainly I was focusing on achieving your requirements.
add_action('init', 'register_cpt_type');
add_filter('pre_term_link', 'change_term_links', 10, 2);
function change_term_links( $termlink, $term ) {
$post_type = isset( get_taxonomy( $term->taxonomy )->object_type[0] ) ? get_taxonomy( $term->taxonomy )->object_type[0] : '';
if( $post_type === 'interest' ) {
$termlink = explode('/', $termlink) != '' ? explode('/', $termlink): '';
unset($termlink[1]);
$termlink = implode('', $termlink);
}
return $termlink;
}
function register_cpt_type() {
$args = array(
'label' => 'Interest',
'description' => 'Add new interest from here',
'public' => true,
'public_queryable' => true,
'exclude_from_search' => false,
'show_ui' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'query_var' => true,
'capability_type' => 'post',
'rewrite' => array(
'slug' => '%country%',
'with_front' => false
),
'hierarchical' => false,
'show_in_rest' => true,
'with_front' => false,
'has_archive' => true,
'menu_icon' => 'dashicons-chart-pie',
'supports' => array('title', 'editor', 'thumbnail', 'excerpt', 'author', 'revisions', 'custom-fields', 'comments')
);
register_post_type('interest', $args);
$args = array(
'label' => 'Country',
'public' => true,
'show_ui' => true,
'query_var' => true,
'show_in_rest' => true,
'hierarchical' => true,
'rewrite' => array(
'slug' => '%country%',
'with_front' => false
),
);
register_taxonomy( 'country', 'interest', $args );
}
add_filter('post_type_link', 'single_cpt_postlink', 10, 2);
function single_cpt_postlink( $post_link, $post ) {
$post_type = get_post_type( $post->ID ) != '' ? get_post_type( $post->ID ) : '';
if( $post_type == 'interest' ) {
$term_slug = get_the_terms( $post->ID, 'country' ) != '' ? get_the_terms( $post->ID, 'country' )[0]->slug : '';
if( ! empty( $term_slug ) ) {
$post_link = str_replace('%country%', $term_slug, $post_link);
}
}
return $post_link;
}
It seems you are wanting to access the CPT single page. In order to do that please follow the code below
add_filter( 'single_template', 'get_interest_single_template' ), 99);
function get_interest_single_template( $single_template_path ) {
if (is_singular('interest')) {
$single_template = plugin_dir_path(__FILE__) . '/single-interest.php' ;
}
return $single_template;
}
Now inside the "single-interest.php". you can var_dump( get_queried_object() ). Which should give you the values of the WP_Post Object data. Since this template is directly coming from a plugin the custom template file should be placed inside a plugin or the custom single-interest file should be placed inside the theme file in this format "single-interest.php". Also, I would like to add the following points, since you are using a custom post type, you do not have to regenerate custom slugs. Because WordPress does regenerate the custom slugs for you. I would recommend you not use 'generate_rewrite_rules' because WordPress did create those slugs for you while creating the custom post type. What you can do is pass the slug value inside the 'parse_request' filter hook. For reference please refer to this page here
I have taken cue from this SO answer and below code worked for me:
// custom url
add_action('init', 'custom_init');
add_filter('post_type_link', 'interest_permalink', 10, 3);
function custom_init() {
global $wp_rewrite;
$interest_structure = '/%country%/%interest%';
$wp_rewrite->add_rewrite_tag("%interest%", '([^/]+)', "interest=");
$wp_rewrite->add_permastruct('interest', $interest_structure, false);
}
function interest_permalink($permalink, $post_id, $leavename) {
$post = get_post($post_id);
$rewritecode = array(
'%country%',
$leavename ? '' : '%postname%',
);
if ('' != $permalink && !in_array($post->post_status, array('draft', 'pending', 'auto-draft'))) {
if (strpos($permalink, '%country%') !== FALSE) {
$terms = wp_get_object_terms($post->ID, 'country');
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) {
$country = $terms[0]->slug;
} else {
$country = 'unassigned_country';
}
}
$countryreplace = array(
$country,
$post->post_name,
);
$permalink = str_replace($rewritecode, $countryreplace, $permalink);
} else {
}
return $permalink;
}

Wordpress: Archive page with Filter doesn't work (ACF)

Im trying to filter my custom post types by a checkbox field of ACF.
I work with this tutorial: https://www.advancedcustomfields.com/resources/creating-wp-archive-custom-field-filter/
Now I got the problem that nothing change, when ich filter over the checkboxes on the archive page of the custom post type. It generates only the right URL but doesn't filter the posts.
Does some have any idea why?
function.php:
// array of filters (field key => field name)
$GLOBALS['my_query_filters'] = array(
'mitglieder' => 'mitglieder'
);
// action
function my_pre_get_posts( $query ) {
// bail early if is in admin
if( is_admin() ) return;
// bail early if not main query
// - allows custom code / plugins to continue working
if( !$query->is_main_query() ) return;
// get meta query
$meta_query = $query->get('meta_query');
// loop over filters
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
// get the value for this filter
// eg: http://www.website.com/events?city=melbourne,sydney
$value = explode(',', $_GET[ $name ]);
// append meta query
$meta_query = array(
array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
)
);
}
// update meta query
$query->set('meta_query', $meta_query );
}
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
register_taxonomy_for_object_type('category', 'projekte'); // Register Taxonomies for Category
$labels = array(
'name' => __('Projekte', 'projekte'), // Rename these to suit
'singular_name' => __('Projekt', 'projekte'),
'add_new' => __('Projekt hinzufügen', 'projekte'),
'add_new_item' => __('Neues Projekt hinzufügen', 'projekte'),
'edit' => __('Bearbeiten', 'projekte'),
'edit_item' => __('Projekt bearbeiten', 'projekte'),
'new_item' => __('Neues Projekt', 'projekte'),
'view' => __('Anschauen', 'projekte'),
'view_item' => __('Projekt anschauen', 'projekte'),
'search_items' => __('Projekte durchsuchen', 'projekte'),
'not_found' => __('Projekt wurde nicht gefunden', 'projekte'),
'not_found_in_trash' => __('Projekt wurde nicht im Papierkorb gefunden', 'projekte')
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'hierarchical' => true, // Allows your posts to behave like Hierarchy Pages
'has_archive' => true,
'supports' => array(
'title',
'excerpt'
), // Go to Dashboard Custom HTML5 Blank post for supports
'can_export' => true, // Allows export in Tools > Export
'taxonomies' => array(
'category',
) // Add Category and Post Tags support
);
register_post_type('projekte', $args);
archive-projekte.php:
<div id="archive-filters">
<?php foreach( $GLOBALS['my_query_filters'] as $key => $name ):
// get the field's settings without attempting to load a value
$field = get_field_object($key, false, false);
// set value if available
if( isset($_GET[ $name ]) ) {
$field['value'] = explode(',', $_GET[ $name ]);
}
// create filter
?>
<div class="filter" data-filter="<?php echo $name; ?>">
<?php create_field( $field ); ?>
</div>
<?php endforeach; ?>
</div>
<script type="text/javascript">
(function($) {
// change
$('#archive-filters').on('change', 'input[type="checkbox"]', function(){
// vars
var url = '<?php echo home_url('projekte'); ?>';
args = {};
// loop over filters
$('#archive-filters .filter').each(function(){
// vars
var filter = $(this).data('filter'),
vals = [];
// find checked inputs
$(this).find('input:checked').each(function(){
vals.push( $(this).val() );
});
// append to args
args[ filter ] = vals.join(',');
});
// update url
url += '?';
// loop over args
$.each(args, function( name, value ){
url += name + '=' + value + '&';
});
// remove last &
url = url.slice(0, -1);
// reload page
window.location.replace( url );
});
$('.button.acf-add-checkbox').parent().remove();
})(jQuery);
</script>
<div class="projekt-archive">
<?php
$args = array(
'post_type' => 'projekte',
'post_status' => 'publish',
'posts_per_page' => '-1'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : ?>
......
<?php
endwhile;
endif;
?>
<?php wp_reset_query(); ?>
I used your code to try and recreate your issue and ran into a number of issues but got it working. On the link you supplied the video tutorial does things differently to the sample code.
The first thing I noticed is that you are changing the $query in the functions then redefining it in archive-projekte.php
$args = array(
'post_type' => 'projekte',
'post_status' => 'publish',
'posts_per_page' => '-1'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) :
//......
endwhile;
endif;
wp_reset_query();
you can just use a version of the standard loop instead
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//.......
}
}
Secondly when I set the advanced custom field(mitglieder) in Wordpress admin to be a checkbox it is then rendered as a checkbox on the front end by create_field() in the filter div but the problem is that checkboxes are saved in the meta data as serialized data so it didn't work so I changed the advanced custom field to a radio button it all works fine.
The new issue created by this is that the filter div now has radio buttons. So I watched the video tutorial and output checkboxes using a foreach loop on $field instead of using create_field, this means that the javascript needs to be changed also.
Now the only issue remains is if you need you advanced custom field to be checkbox sothat one of your projekte posts to have more than one mitglieder value then you would need to work with the serialized meta data in order to make the filter work correctly.
This works like ACF example video which uses houses and bedrooms and in that case a house cannot be a 2 bedroom house and a 3 bedroom house at the same time.

WordPress post rewrite rule causes pages to 404

I need my post permalinks to include a custom taxonomy value, type, like this:
http://staging.mysite.com/article/post-title
Where article is that post's type taxonomy value. I've gotten this to work, but the problem I'm running into is that now all of my site's pages are 404ing. My custom post type and normal post urls work as intended, it's just page urls that are broken. Here is the code that causes the issue with page urls:
// Type taxonomy (no issues here)
function create_type_taxonomy() {
register_taxonomy(
'type',
'post',
array(
'labels' => array(
'name' => 'Type',
'add_new_item' => 'Add New Type',
'new_item_name' => 'New Type'
),
'show_ui' => true,
'show_tagcloud' => false,
'hierarchical' => false,
'rewrite' => array(
'slug' => 'type',
'with_front' => true
),
)
);
}
add_action( 'init', 'create_type_taxonomy', 0 );
add_action( 'init', 'st_default_post_type', 1 );
// Re-register built-in posts with a custom rewrite rule
function st_default_post_type() {
register_post_type( 'post', array(
'labels' => array(
'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
),
'public' => true,
'_builtin' => false,
'_edit_link' => 'post.php?post=%d',
'capability_type' => 'post',
'map_meta_cap' => true,
'hierarchical' => false,
'rewrite' => array( 'slug' => '%type%', 'with_front' => false ), // custom rewrite rule
'query_var' => false,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
) );
}
add_filter('post_type_link', 'st_posts_permalink_structure', 10, 4);
// Replace custom rewrite rule on posts (%type%) with the taxonomy value
function st_posts_permalink_structure($post_link, $post, $leavename, $sample){
if ($post->post_type != 'post') {
var_dump($post->post_type);
return $post_link;
}
else{
if (strpos($post_link, '%type%') === FALSE){
return $post_link;
}
$post = get_post($post);
if (!$post){
return $post_link;
}
$terms = wp_get_object_terms($post->ID, 'type');
if ( !is_wp_error($terms) && !empty($terms) && is_object($terms[0]) ){
$taxonomy_slug = $terms[0]->slug;
}
else{
$taxonomy_slug = 'type';
}
return str_replace('%type%', $taxonomy_slug, $post_link);
}
}
Hoping another set of eyes might catch something that would cause page permalinks to 404. I've already tried just changing the permalinks setting in the admin to be /%type%/%postname%/, but this has the same issue. I found a couple other questions here that looked like the same issue I have, but none of them were answered:
WordPress Taxonomy Causing Pages to 404
When I add custom post type permalink rewrite, my regular post permalinks stop working. Can't get both to work at the same time
Hi I know this is a late answer, I had this issue today and found this info:
https://rudrastyh.com/wordpress/taxonomy-slug-in-post-type-url.html
Credit goes to: Misha Rudrastyh for this answer obviously, he has not used the rewrite declaration in his cpt instead seems to use filters to do the same thing, this got me past all my posts and pages 404ing.
To quote his code for posterity, he explained to use this code to solve the issue:
function rudr_post_type_permalink($permalink, $post_id, $leavename) {
$post_type_name = 'post_type_name'; // post type name, you can find it in admin area or in register_post_type() function
$post_type_slug = 'post_type_name'; // the part of your product URLs, not always matches with the post type name
$tax_name = 'custom_taxonomy_name'; // the product categories taxonomy name
$post = get_post( $post_id );
if ( strpos( $permalink, $post_type_slug ) === FALSE || $post->post_type != $post_type_name ) // do not make changes if the post has different type or its URL doesn't contain the given post type slug
return $permalink;
$terms = wp_get_object_terms( $post->ID, $tax_name ); // get all terms (product categories) of this post (product)
if ( !is_wp_error( $terms ) && !empty( $terms ) && is_object( $terms[0] ) ) // rewrite only if this product has categories
$permalink = str_replace( $post_type_slug, $terms[0]->slug, $permalink );
return $permalink;
}
add_filter('request', 'rudr_post_type_request', 1, 1 );
function rudr_post_type_request( $query ){
global $wpdb;
$post_type_name = 'post_type_name'; // specify your own here
$tax_name = 'custom_taxonomy_name'; // and here
$slug = $query['attachment']; // when we change the post type link, WordPress thinks that these are attachment pages
// get the post with the given type and slug from the database
$post_id = $wpdb->get_var(
"
SELECT ID
FROM $wpdb->posts
WHERE post_name = '$slug'
AND post_type = '$post_type_name'
"
);
$terms = wp_get_object_terms( $post_id, $tax_name ); // our post should have the terms
if( isset( $slug ) && $post_id && !is_wp_error( $terms ) && !empty( $terms ) ) : // change the query
unset( $query['attachment'] );
$query[$post_type_name] = $slug;
$query['post_type'] = $post_type_name;
$query['name'] = $slug;
endif;
return $query;
}
In addition like I said you will not need to declare the "rewrite" portion in the CPT arguments, you can leave the filters to handle that "after the fact" type thing.

Wordpress Meta Box plugin, retrieving image url from custom post type

Having a bit of bother with the Wordpress Meta Box plugin, specifically with retrieving an image url from an image added to a custom post type.
I'm creating meta boxes in a custom plugin, like so:
add_filter( 'rwmb_meta_boxes', 'xxx_meta_register_meta_boxes' );
function xxx_meta_register_meta_boxes( $meta_boxes )
{
$prefix = 'xxx_meta_';
$meta_boxes[] = array(
'title' => esc_html__( 'Retailer Information', '' ),
'id' => 'advanced',
'post_types' => array( 'xxx_retailers' ),
'autosave' => true,
'fields' => array(
// PLUPLOAD IMAGE UPLOAD (WP 3.3+)
array(
'name' => esc_html__( 'Retailer Logo', '' ),
'id' => "{$prefix}plupload",
'type' => 'plupload_image',
'max_file_uploads' => 1,
),
// URL
array(
'name' => esc_html__( 'Link', '' ),
'id' => "{$prefix}url",
'desc' => esc_html__( 'Clicking the retailer logo will take the user to this URL', '' ),
'type' => 'url',
'std' => 'xxx',
),
)
);
return $meta_boxes;
}
So far so good, these boxes are relevant to a custom post type 'xxx_retailers'.
The problem comes with retrieving this data. I want to display my retailers in a widget. I've chopped and changed another piece of code I've used previously, but it's not returning the image URL, just the ID. Unfortunately I don't know enough php to figure out why.
// Create Retailers Widget
// Create the widget
class Retailers_Widget extends WP_Widget {
function __construct() {
parent::__construct(
// base ID of the widget
'retailers_widget',
// name of the widget
__('XXX Retailers List', '' ),
// widget options
array (
'description' => __( 'Shows a list of retailer logos', '' )
)
);
}
function widget( $args, $instance ) {
// kick things off
extract( $args );
echo $before_widget;
echo $before_title . 'Retailers' . $after_title;
// Pull through Retailers
$xxxretailers = get_posts(array(
'post_type' => 'xxx_retailers',
'orderby' => 'title',
'order' => 'asc',
));
// Display for each Retailer
foreach ($xxxretailers as $xxxretailer) {
$custom = get_post_custom($xxxretailer->ID);
$meta_ret_img = $custom["xxx_meta_plupload"][0];
$meta_ret_url = $custom["xxx_meta_url"][0];
// Display Retailers
echo "<li><a href='{$meta_ret_url}'><img src='{$meta_ret_img}' /></a></li>";
}
}
};
// Register widget
function register_retailers_widget() {
register_widget( 'Retailers_Widget' );
}
add_action( 'widgets_init', 'register_retailers_widget' );
The URLs are coming through correctly, so I know this is a problem with the line
$meta_ret_img = $custom["xxx_meta_plupload"][0];
But I can't figure out how to get the image URL from the data I presume is stored as an array. Any ideas?
Edit:
I should have mentioned, in a single post I can get a single image with:
$images = rwmb_meta( 'xxx_meta_plupload', 'size=medium' );
if ( !empty( $images ) ) {
foreach ( $images as $image ) {
echo "<img src='{$image['url']}' />";
}
}
But I want to show images from all my retailers post types, to create a list of logos.
Replace this statement:
$meta_ret_img = $custom["xxx_meta_plupload"][0];
with this:
$meta_ret_img_array = wp_get_attachment_image_src($custom["xxx_meta_plupload"][0]);
$meta_ret_img = $meta_ret_img_array[0];
also please remove all these curly braces from src and href attributes from your code.
if you are interested in any particular size of the image, then see the official document of wp_get_attachment_image_src() function here.
For e.g. for medium size image you can write it as:
wp_get_attachment_image_src($custom["xxx_meta_plupload"][0], 'medium');

How to restrict Subscriber to one custom post type and restraint them from editing other post

Hi I'm trying to make a custom section for a wordpress site and I need to give some access to my subscriber.
I created a custom post type (boat). What I need to do is :
1 - Grant access to any subcriber to my custom post type.
2 - Grant permission to any subscribers to publish / edit / delete / upload file only in their own post (+ permission to assign their post to one of the already created taxonomy I made)
3 - Restrict them from viewing / editing other subscribers post
4 - I don't want the subscriber to see something else than their profile and the custom post type section
I tried to use role scoper, wp-Members and Capability Manager but none of them seem to do exactly what I want. If you know how to do it I'd really appreciate
Thanks in advance for the help.
Here is what I did, instead of granting subscriber all these permission, I upgraded all my subscribers to contributor.
I changed the capability of my custom post type to:
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'boat' ),
'capability_type' => 'post',
'capabilities' => array(
'publish_posts' => 'edit_posts',//contributor can edit
'edit_others_posts' => 'update_core',//administrator can see other
'delete_posts' => 'update_core',//administrator can see other
'delete_others_posts' => 'update_core',//administrator can see other
'read_private_posts' => 'update_core',//administrator can see other
'edit_post' => 'edit_posts',//contributor can edit
'delete_post' => 'update_core',//administrator can see other
'read_post' => 'edit_posts',//contributor can edit
),
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title','revision' )
);
register_post_type("boat", $args);
Then I added some custom function I found at different webpage :
This one hide the menu I dont want the contributor to see
source : source 1
and : source 2
function remove_menus(){
$author = wp_get_current_user();
if(isset($author->roles[0])){
$current_role = $author->roles[0];
}else{
$current_role = 'no_role';
}
if($current_role == 'contributor'){
remove_menu_page( 'index.php' ); //Dashboard
remove_menu_page( 'edit.php' ); //Posts
remove_menu_page( 'upload.php' ); //Media
remove_menu_page( 'tools.php' ); //Tools
remove_menu_page( 'edit-comments.php' ); //Comments
remove_menu_page( 'edit.php?post_type=my_other_custom_post_type_I_want_to_hide' );
}
}
add_action( 'admin_menu', 'remove_menus' );
Then I restricted contributor from seings other post with :
from : source 3
add_action( 'load-edit.php', 'posts_for_current_contributor' );
function posts_for_current_contributor() {
global $user_ID;
if ( current_user_can( 'contributor' ) ) {
if ( ! isset( $_GET['author'] ) ) {
wp_redirect( add_query_arg( 'author', $user_ID ) );
exit;
}
}
}
And finally I allowed contributor to upload file with :
from source 4
add_action('admin_init', 'allow_contributor_uploads');
function allow_contributor_uploads() {
$contributor = get_role('contributor');
$contributor->add_cap('upload_files');
}
Since I got a bunch of custom field in my custom post type I made with ACF (Advance custom field) I restricted the media upload to only local post so my contributor cant use media from other people.
I hope this will help someone! :)

Categories