Doesn't work auto save custom fields in Wordpress - wordpress

I'm using Smashing Magazine tutorial step by step. But there is doesn't work auto save in my custom fields. After click publish and update button the fields are empty. How to resolve the issue.
function my_custom_post_movie() {
$labels = array(
'name' => _x( 'movies', 'post type general name' ),
'singular_name' => _x( 'movie', 'post type singular name' ),
'add_new' => _x( 'Add New', 'book' ),
'add_new_item' => __( 'Add New movie' ),
'edit_item' => __( 'Edit movie' ),
'new_item' => __( 'New movie' ),
'all_items' => __( 'All movies' ),
'view_item' => __( 'View movie' ),
'search_items' => __( 'Search movies' ),
'not_found' => __( 'No movies found' ),
'not_found_in_trash' => __( 'No movies found in the Trash' ),
'parent_item_colon' => '',
'menu_name' => 'movies'
);
$args = array(
'labels' => $labels,
'description' => 'Holds our movies and movie specific data',
'public' => true,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
'has_archive' => true,
);
register_post_type( 'movie', $args );
}
add_action( 'init', 'my_custom_post_movie' );
// Register Custom Taxonomies
function my_taxonomies_movie() {
$labels = array(
'name' => _x( 'movie Categories', 'taxonomy general name' ),
'singular_name' => _x( 'movie Category', 'taxonomy singular name' ),
'search_items' => __( 'Search movie Categories' ),
'all_items' => __( 'All movie Categories' ),
'parent_item' => __( 'Parent movie Category' ),
'parent_item_colon' => __( 'Parent movie Category:' ),
'edit_item' => __( 'Edit movie Category' ),
'update_item' => __( 'Update movie Category' ),
'add_new_item' => __( 'Add New movie Category' ),
'new_item_name' => __( 'New movie Category' ),
'menu_name' => __( 'movie Categories' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
);
register_taxonomy( 'movie_category', 'movie', $args );
}
add_action( 'init', 'my_taxonomies_movie', 0 );
// Meta Box
add_action( 'add_meta_boxes', 'movie_date_box' );
function movie_date_box() {
add_meta_box(
'movie_date_box',
__( 'movie date', 'myplugin_textdomain' ),
'movie_date_box_content',
'movie',
'side',
'high'
);
}
function movie_date_box_content( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'movie_date_box_content_nonce' );
echo '<label for="movie_date"></label>';
echo '<input type="text" id="movie_date" name="movie_date" placeholder="enter a date" />';
}
add_action( 'save_post', 'movie_date_box_save' );
function movie_date_box_save( $post_id ) {
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( !wp_verify_nonce( $_POST['movie_date_box_content_nonce'], plugin_basename( __FILE__ ) ) )
return;
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ) )
return;
} else {
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
$movie_date = $_POST['movie_date'];
update_post_meta( $post_id, 'movie_date', $movie_date );
}
Thanks for the help.

Your information is in fact being saved to the database, but it is not being called once the post has been submitted.
Change:
function movie_date_box_content( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'movie_date_box_content_nonce' );
echo '<label for="movie_date"></label>';
echo '<input type="text" id="movie_date" name="movie_date" placeholder="enter a date" />';
}
to the following:
function movie_date_box_content( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'movie_date_box_content_nonce' );
echo '<label for="movie_date"></label>';
echo '<input type="text" id="movie_date" name="movie_date" placeholder="enter a date" value="' . get_post_meta( $post->ID, 'movie_date', true ) . '" />';
}
You were missing value="' . get_post_meta( $post->ID, 'movie_date', true ) . '"
get_post_meta() calls the meta key movie_date from the database and shows it, if there is anything stored in that key.
Also change:
if ( !wp_verify_nonce( $_POST['movie_date_box_content_nonce'], plugin_basename( __FILE__ ) ) )
return;
to the following:
if ( !isset($_POST['movie_date_box_content_nonce']) || !wp_verify_nonce( $_POST['movie_date_box_content_nonce'], plugin_basename( __FILE__ ) ) )
return;
This checks to see if the nonce field is set and not NULL. It takes care of the Undeclared Index notice that shows up in the admin.

Related

Custom post type taxonomy not being replaced in ACF post object field output

I have a custom post type (Photos) and a taxonomy (Locations) setup on my client's website. The permalinks work correctly when accessed using the menus, search, and directly from the custom post type in the WordPress admin panel, but not when accessing them using an Advanced Custom Fields post object field in my Timber/Twig template. The taxonomy portion (%locations%) of the URL is not being replaced. For example, http://example.com/photos/`%locations%`/taj-mahal-and-the-ganges/. The %locations% should be replaced with world and india, which are locations from the custom taxonomy.
The post's custom post object field is being pulled into the template using the following code: {{ __('View photo gallery', textdomain) }}.
I have included my custom post type and taxonomy code below:
function textdomain_register_photos_post_type() {
$args = [
'label' => 'Photo Galleries',
'labels' => [
'singular_name' => _x( 'Photo Gallery', 'singular' ),
'menu_name' => _x( 'Photo Galleries', 'admin menu' ),
'name_admin_bar' => _x( 'Photo Galleries', 'admin bar' ),
'add_new' => _x( 'Add New', 'add new' ),
'add_new_item' => __( 'Add New Photo Gallery' ),
'new_item' => __( 'New Photo Gallery' ),
'edit_item' => __( 'Edit Photo Gallery' ),
'view_item' => __( 'View Photo Gallery' ),
'all_items' => __( 'All Photo Galleries' ),
'search_items' => __( 'Search Photo Galleries' ),
'not_found' => __( 'No photo galleries found.' ),
],
'supports' => array(
'title',
'editor',
'thumbnail'
),
'public' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-format-gallery',
'capability_type' => 'post',
'taxonomies' => [ 'locations', ],
'has_archive' => true,
'delete_with_user' => false,
'rewrite' => [
'slug' => 'photos/%locations%',
'with_front' => false,
],
];
register_post_type( 'photos', $args );
};
add_action( 'init', 'textdomain_register_photos_post_type' );
function textdomain_register_locations_taxonomy() {
$args = [
'labels' => [
'name' => _x( 'Locations', 'taxonomy general name' ),
'singular_name' => _x( 'Location', 'taxonomy singular name' ),
'search_items' => __( 'Search Locations' ),
'all_items' => __( 'All Locations' ),
'parent_item' => __( 'Parent Location' ),
'parent_item_colon' => __( 'Parent Location:' ),
'edit_item' => __( 'Edit Location' ),
'update_item' => __( 'Update Location' ),
'add_new_item' => __( 'Add New Location' ),
'new_item_name' => __( 'New Location Name' ),
'menu_name' => __( 'Locations' ),
],
'hierarchical' => true,
'rewrite' => [
'slug' => 'locations',
'hierarchical' => true,
],
];
register_taxonomy( 'locations', [ 'photos' ], $args );
};
add_action( 'init', 'textdomain_register_locations_taxonomy' );
add_filter( 'post_type_link', 'textdomain_post_type_link', 10, 2 );
function textdomain_post_type_link( $post_link, $post ) {
// Bail out if not photos post type.
if ( 'photos' !== $post->post_type ) {
return $post_link;
}
$taxonomy = 'locations';
$terms = get_the_terms( get_the_ID(), $taxonomy );
$slug = [];
foreach ( $terms as $term ) {
if ( $term->parent == 0 ) {
array_unshift( $slug, sanitize_title_with_dashes( $term->name ) );
} else {
array_push( $slug, sanitize_title_with_dashes( $term->name ) );
}
}
if ( ! empty( $slug ) ) {
$post_link = str_replace( '%' . $taxonomy . '%', join( '/', $slug ), $post_link );
}
return $post_link;
}
I have saved my permalinks multiple times and have flush_rewrite_rules(); at the bottom of my theme's functions file.
Update
WordPress is displaying this warning Invalid argument supplied foreach() on line 422 of the functions.php file. The code is as follows:
$taxonomy = 'locations';
$terms = get_the_terms( get_the_ID(), $taxonomy );
$slug = [];
foreach ( $terms as $term ) {
if ( $term->parent == 0 ) {
array_unshift( $slug, sanitize_title_with_dashes( $term->name ) );
} else {
array_push( $slug, sanitize_title_with_dashes( $term->name ) );
}
}
I am not sure if this could be causing the issue, but my PHP knowledge is limited.
Any tips or suggestions on this issue are greatly appreciated.
I figured out the issue was related to how the post ID was being retrieved for the taxonomies. I reviewed the get_the_terms function reference and found that get_the_ID() needed to be replaced by $post->ID in the following line: $terms = get_the_terms( $post->ID, $taxonomy );. My updated and working function is below.
add_filter( 'post_type_link', 'textdomain_post_type_link', 10, 2 );
function textdomain_post_type_link( $post_link, $post ) {
// Bail out if not photos post type.
if ( 'photos' !== $post->post_type ) {
return $post_link;
}
$taxonomy = 'locations';
// Replaced get_the_ID() with $post->ID
$terms = get_the_terms( $post->ID, $taxonomy );
$slug = [];
foreach ( $terms as $term ) {
if ( $term->parent == 0 ) {
array_unshift( $slug, sanitize_title_with_dashes( $term->name ) );
} else {
array_push( $slug, sanitize_title_with_dashes( $term->name ) );
}
}
if ( ! empty( $slug ) ) {
$post_link = str_replace( '%' . $taxonomy . '%', join( '/', $slug ), $post_link );
}
return $post_link;
}

Wordpress get_the_terms for custom Taxonomy

Within an archive page, I'm trying to show the a custom taxonomy (called location) along with each post title, category and tag. I can't get the 'get_the_terms' to work.
The post title, category and tag is working perfectly. The taxonomy doesn't work.
<div class="post-listing">
<h4><?php the_title(); ?></h4>
<p><?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?></p>
<p><?php $tags = get_the_tags(); foreach($tags as $tag) { echo "$tag->name"; } ?></p>
<p><?php $terms = get_the_terms( 'locations' ); foreach($terms as $term) { echo "$term->name"; } ?></p>
</div>
This is my functions.php code.
//hook into the init action and call create_locations_nonhierarchical_taxonomy when it fires
add_action( 'init', 'create_locations_nonhierarchical_taxonomy', 0 );
function create_locations_nonhierarchical_taxonomy() {
// Labels part for the GUI
$labels = array(
'name' => _x( 'Locations', 'taxonomy general name' ),
'singular_name' => _x( 'Location', 'taxonomy singular name' ),
'search_items' => __( 'Search Locations' ),
'popular_items' => __( 'Popular Locations' ),
'all_items' => __( 'All Locations' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Edit Location' ),
'update_item' => __( 'Update Location' ),
'add_new_item' => __( 'Add New Location' ),
'new_item_name' => __( 'New Location Name' ),
'separate_items_with_commas' => __( 'Separate locations with commas' ),
'add_or_remove_items' => __( 'Add or remove locations' ),
'choose_from_most_used' => __( 'Choose from the most used locations' ),
'menu_name' => __( 'Locations' ),
);
// Now register the non-hierarchical taxonomy like tag
register_taxonomy('locations','post',array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'update_count_callback' => '_update_post_term_count',
'query_var' => true,
'rewrite' => array( 'slug' => 'location' ),
));
}
Any ideas? It's driving me mad!
There are two parameters of get_the_terms function. They are $post and $taxonomy. Unlike the other "get_the_xxxx" functions that you can skip the $post (post object or post ID) parameter inside the loop, you must add the post object or post ID to the first parameter.
I think you should write
$terms = get_the_terms( $post, 'locations' );
Instead of
$terms = get_the_terms( 'locations' );
Documentation: https://developer.wordpress.org/reference/functions/get_the_terms/

Custom post meta showing on localhost, but not live server?

I'm having an issue and, honestly, I have absolutely no idea what's going on...
I have some custom meta fields for my custom post type (called review). On my local installation, they appear and work perfectly:
However, on live, they don't show up! Completely vanished!
The panel is selected in Screen Options too, so that's not the issue:
Here is the code for my entire custom post type... perhaps I've done something stupid?
<?php
// Register Custom Post Type
function review() {
$labels = array(
'name' => 'Reviews',
'singular_name' => 'Review',
'menu_name' => 'Reviews',
'name_admin_bar' => 'Review',
'archives' => 'Review Archives',
'parent_item_colon' => 'Parent Item:',
'all_items' => 'All Items',
'add_new_item' => 'Add New Item',
'add_new' => 'Add New',
'new_item' => 'New Item',
'edit_item' => 'Edit Item',
'update_item' => 'Update Item',
'view_item' => 'View Item',
'search_items' => 'Search Item',
'not_found' => 'Not found',
'not_found_in_trash' => 'Not found in Trash',
'featured_image' => 'Featured Image',
'set_featured_image' => 'Set featured image',
'remove_featured_image' => 'Remove featured image',
'use_featured_image' => 'Use as featured image',
'insert_into_item' => 'Insert into item',
'uploaded_to_this_item' => 'Uploaded to this item',
'items_list' => 'Items list',
'items_list_navigation' => 'Items list navigation',
'filter_items_list' => 'Filter items list',
);
$args = array(
'label' => 'Review',
'description' => 'A product review',
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions'),
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-edit',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'review', $args );
}
add_action( 'init', 'review', 0 );
//Review options meta
/**
* Generated by the WordPress Meta Box generator
* at http://jeremyhixon.com/tool/wordpress-meta-box-generator/
*/
function review_options_get_meta( $value ) {
global $post;
$field = get_post_meta( $post->ID, $value, true );
if ( ! empty( $field ) ) {
return is_array( $field ) ? stripslashes_deep( $field ) : stripslashes( wp_kses_decode_entities( $field ) );
} else {
return false;
}
}
function review_options_add_meta_box() {
add_meta_box(
'review_options-review-options',
__( 'Review options', 'review_options' ),
'review_options_html',
'review',
'core',
'high'
);
}
add_action( 'add_meta_boxes', 'review_options_add_meta_box' );
function review_options_html( $post) {
wp_nonce_field( '_review_options_nonce', 'review_options_nonce' ); ?>
<p>Options for your reviews</p>
<p>
<label for="review_options_review_score"><?php _e( 'Review Score', 'review_options' ); ?></label><br>
<select name="review_options_review_score" id="review_options_review_score" style="width: 50%;">
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '1' ) ? 'selected' : '' ?>>1</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '2' ) ? 'selected' : '' ?>>2</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '3' ) ? 'selected' : '' ?>>3</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '4' ) ? 'selected' : '' ?>>4</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '5' ) ? 'selected' : '' ?>>5</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '6' ) ? 'selected' : '' ?>>6</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '7' ) ? 'selected' : '' ?>>7</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '8' ) ? 'selected' : '' ?>>8</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '9' ) ? 'selected' : '' ?>>9</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '10' ) ? 'selected' : '' ?>>10</option>
</select>
</p> <p>
<label for="review_options_review_title_colour"><?php _e( 'Review title colour', 'review_options' ); ?></label><br>
<select name="review_options_review_title_colour" id="review_options_review_title_colour">
<option <?php echo (review_options_get_meta( 'review_options_review_title_colour' ) === '' ) ? 'selected' : '' ?>>Default</option>
<option <?php echo (review_options_get_meta( 'review_options_review_title_colour' ) === 'black' ) ? 'selected' : '' ?>>Black</option>
<option <?php echo (review_options_get_meta( 'review_options_review_title_colour' ) === 'white' ) ? 'selected' : '' ?>>White</option>
</select>
</p><?php
}
function review_options_save( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( ! isset( $_POST['review_options_nonce'] ) || ! wp_verify_nonce( $_POST['review_options_nonce'], '_review_options_nonce' ) ) return;
if ( ! current_user_can( 'edit_post', $post_id ) ) return;
if ( isset( $_POST['review_options_review_score'] ) )
update_post_meta( $post_id, 'review_options_review_score', esc_attr( $_POST['review_options_review_score'] ) );
if ( isset( $_POST['review_options_review_title_colour'] ) )
update_post_meta( $post_id, 'review_options_review_title_colour', esc_attr( $_POST['review_options_review_title_colour'] ) );
}
add_action( 'save_post', 'review_options_save' );
/*
Usage: review_options_get_meta( 'review_options_review_score' )
Usage: review_options_get_meta( 'review_options_review_title_colour' )
*/
?>
Or perhaps it's something to do with my only other post type?
<?php // Register Custom Post Type
function product() {
$labels = array(
'name' => _x( 'Products', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Product', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Product', 'text_domain' ),
'name_admin_bar' => __( 'Product', 'text_domain' ),
'archives' => __( 'Products', 'text_domain' ),
'parent_item_colon' => __( 'Product', 'text_domain' ),
'all_items' => __( 'All Products', 'text_domain' ),
'add_new_item' => __( 'Add New Product', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Product', 'text_domain' ),
'edit_item' => __( 'Edit Product', 'text_domain' ),
'update_item' => __( 'Update Product', 'text_domain' ),
'view_item' => __( 'View Product', 'text_domain' ),
'search_items' => __( 'Search Products', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into Product', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this Product', 'text_domain' ),
'items_list' => __( 'Product list', 'text_domain' ),
'items_list_navigation' => __( 'Product list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter Product list', 'text_domain' ),
);
$args = array(
'label' => __( 'Product', 'text_domain' ),
'description' => __( 'A product', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'thumbnail', ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 8,
'menu_icon' => 'dashicons-archive',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'product', $args );
}
add_action( 'init', 'product', 0 );
//Creation of Meta Box for post type "destination_category" (Start)
add_action( 'admin_init', 'my_destination_category' );
//destination_sub_category_admin - is the required HTML id attribute
//Select Destination Sub Category - is the text visible in the heading of the meta box section
//display_destination_subcategory_meta_box - is the callback which renders the contents of the meta box
//destination_category - is the name of the custom post type where the meta box will be displayed
// normal - defines the part of the page where the edit screen section should be shown
// high - defines the priority within the context where the boxes should show
function my_destination_category() {
foreach( array( 'post', 'review' ) as $pt )
add_meta_box(
'destination_sub_category_admin',
'Select Destination Sub Category',
'display_destination_subcategory_meta_box',
$pt,
'normal',
'high');
function display_destination_subcategory_meta_box( $select_category ) {
// Retrieve Current Selected Category ID based on the Category Created
global $wpdb;
$selectcat="SELECT * FROM ".$wpdb->prefix."posts WHERE `post_type`='product' AND `post_status`='publish' ORDER BY `ID` DESC";
$resultant = $wpdb->get_results($selectcat);
$rescount=count($resultant);
$category_selected_id = intval( get_post_meta( $select_category->ID, 'destination_category_id', true ) );
?>
<table>
<tr>
<td style="width: 150px">Select Category</td>
<td>
<select style="width: 100px" name="category_selection" id="meta_box_category" style="float:left; width:50%; !important">
<?php
if($rescount==0)
{?>
<option value="null">No Posts have been created</option>
<?php
}
else
{
// Generate all items of drop-down list
?>
<option value="">None</option>
<?php
foreach($resultant as $singleresultant)
{
?>
<option value="<?php echo $singleresultant->ID; ?>" <?php echo selected( $singleresultant->ID, $category_selected_id ); ?>>
<?php echo $singleresultant->post_title; ?>
</option>
<?php
}
}
?>
</select>
</td>
</tr>
</table>
<?php
}
// Registering a Save Post Function
add_action( 'save_post', 'destination_admin_sub_category', 10, 2 );
function destination_admin_sub_category( $select_category_id, $select_category ) {
if ( $select_category->post_type == 'post' || 'review' ) {
if ( isset( $_POST['category_selection'] ) && $_POST['category_selection'] != '' ) {
echo update_post_meta( $select_category_id, 'destination_category_id', $_POST['category_selection'] );
} }
}
}
/**
* Generated by the WordPress Meta Box Generator at
*/
class Rational_Meta_Box {
private $screens = array(
'product',
);
private $fields = array(
array(
'id' => 'box-art',
'label' => 'Box Art',
'type' => 'media',
),
array(
'id' => 'developer',
'label' => 'Developer',
'type' => 'text',
),
array(
'id' => 'publisher',
'label' => 'Publisher',
'type' => 'text',
),
array(
'id' => 'release-date',
'label' => 'Release Date',
'type' => 'date',
),
);
/**
* Class construct method. Adds actions to their respective WordPress hooks.
*/
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
add_action( 'admin_footer', array( $this, 'admin_footer' ) );
add_action( 'save_post', array( $this, 'save_post' ) );
}
/**
* Hooks into WordPress' add_meta_boxes function.
* Goes through screens (post types) and adds the meta box.
*/
public function add_meta_boxes() {
foreach ( $this->screens as $screen ) {
add_meta_box(
'product-options',
__( 'Product Options', 'product-options' ),
array( $this, 'add_meta_box_callback' ),
$screen,
'advanced',
'core'
);
}
}
/**
* Generates the HTML for the meta box
*
* #param object $post WordPress post object
*/
public function add_meta_box_callback( $post ) {
wp_nonce_field( 'product_options_data', 'product_options_nonce' );
echo 'Options for products';
$this->generate_fields( $post );
}
/**
* Hooks into WordPress' admin_footer function.
* Adds scripts for media uploader.
*/
public function admin_footer() {
?><script>
// https://codestag.com/how-to-use-wordpress-3-5-media-uploader-in-theme-options/
jQuery(document).ready(function($){
if ( typeof wp.media !== 'undefined' ) {
var _custom_media = true,
_orig_send_attachment = wp.media.editor.send.attachment;
$('.rational-metabox-media').click(function(e) {
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(this);
var id = button.attr('id').replace('_button', '');
_custom_media = true;
wp.media.editor.send.attachment = function(props, attachment){
if ( _custom_media ) {
$("#"+id).val(attachment.url);
} else {
return _orig_send_attachment.apply( this, [props, attachment] );
};
}
wp.media.editor.open(button);
return false;
});
$('.add_media').on('click', function(){
_custom_media = false;
});
}
});
</script><?php
}
/**
* Generates the field's HTML for the meta box.
*/
public function generate_fields( $post ) {
$output = '';
foreach ( $this->fields as $field ) {
$label = '<label for="' . $field['id'] . '">' . $field['label'] . '</label>';
$db_value = get_post_meta( $post->ID, 'product_options_' . $field['id'], true );
switch ( $field['type'] ) {
case 'media':
$input = sprintf(
'<input class="regular-text" id="%s" name="%s" type="text" value="%s"> <input class="button rational-metabox-media" id="%s_button" name="%s_button" type="button" value="Upload" />',
$field['id'],
$field['id'],
$db_value,
$field['id'],
$field['id']
);
break;
default:
$input = sprintf(
'<input %s id="%s" name="%s" type="%s" value="%s">',
$field['type'] !== 'color' ? 'class="regular-text"' : '',
$field['id'],
$field['id'],
$field['type'],
$db_value
);
}
$output .= $this->row_format( $label, $input );
}
echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
}
/**
* Generates the HTML for table rows.
*/
public function row_format( $label, $input ) {
return sprintf(
'<tr><th scope="row">%s</th><td>%s</td></tr>',
$label,
$input
);
}
/**
* Hooks into WordPress' save_post function
*/
public function save_post( $post_id ) {
if ( ! isset( $_POST['product_options_nonce'] ) )
return $post_id;
$nonce = $_POST['product_options_nonce'];
if ( !wp_verify_nonce( $nonce, 'product_options_data' ) )
return $post_id;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
foreach ( $this->fields as $field ) {
if ( isset( $_POST[ $field['id'] ] ) ) {
switch ( $field['type'] ) {
case 'email':
$_POST[ $field['id'] ] = sanitize_email( $_POST[ $field['id'] ] );
break;
case 'text':
$_POST[ $field['id'] ] = sanitize_text_field( $_POST[ $field['id'] ] );
break;
}
update_post_meta( $post_id, 'product_options_' . $field['id'], $_POST[ $field['id'] ] );
} else if ( $field['type'] === 'checkbox' ) {
update_post_meta( $post_id, 'product_options_' . $field['id'], '0' );
}
}
}
}
new Rational_Meta_Box;
?>
Either way, I have absolutely no idea why it's working perfectly locally and messing up on my live server... it's baffling!
Thanks in advance for your help!

WordPress: Remove "Parent" dropdown from category form

Hi I've downloaded a plugin "Simple Staff List" and it does what I need but I don't want editors to create a sub-category. How can I remove/hide the "Parent" selectbox on the form?
Add bellow code in your current theme function.php file.
add_action( 'admin_head-edit-tags.php', 'wpse_58799_remove_parent_category' );
function wpse_58799_remove_parent_category()
{
if ( 'category' != $_GET['taxonomy'] )
return;
$parent = 'parent()';
if ( isset( $_GET['action'] ) )
$parent = 'parent().parent()';
?>
<script type="text/javascript">
jQuery(document).ready(function($)
{
$('label[for=parent]').<?php echo $parent; ?>.remove();
});
</script>
<?php
}
You can use set these options in
register_taxonomy() func
'hierarchical' => false,
'parent_item' => null,
'parent_item_colon' => null,
This would remove the parent field.
This will remove the parent dropdown from both the taxonomy and post new/edit screens.
<?php
function remove_tax_parent_dropdown() {
$screen = get_current_screen();
if ( 'category' == $screen->taxonomy ) {
if ( 'edit-tags' == $screen->base ) {
$parent = "$('label[for=parent]').parent()";
} elseif ( 'term' == $screen->base ) {
$parent = "$('label[for=parent]').parent().parent()";
}
} elseif ( 'post' == $screen->post_type ) {
$parent = "$('#newcategory_parent')";
} else {
return;
}
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
<?php echo $parent; ?>.remove();
});
</script>
<?php
}
add_action( 'admin_head-edit-tags.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-term.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-post.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-post-new.php', 'remove_tax_parent_dropdown' );
If you want to disable "hierarchical" itself from category taxonomy, add this code in your function.php.
add_action('init', function(){
global $wp_taxonomies;
$wp_taxonomies['category']->hierarchical = false;
});
Add bellow code in your current theme function.php file.
function custom_taxonomy() {
$labels = array(
'name' => _x( 'Brands', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'Brand', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Taxonomy', 'text_domain' ),
'all_items' => __( 'All Items', 'text_domain' ),
'parent_item' => __( 'Parent Item', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'new_item_name' => __( 'New Item Name', 'text_domain' ),
'add_new_item' => __( 'Add New Item', 'text_domain' ),
'edit_item' => __( 'Edit Item', 'text_domain' ),
'update_item' => __( 'Update Item', 'text_domain' ),
'view_item' => __( 'View Item', 'text_domain' ),
'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
'add_or_remove_items' => __( 'Add or remove items', 'text_domain' ),
'choose_from_most_used' => __( 'Choose from the most used', 'text_domain' ),
'popular_items' => __( 'Popular Items', 'text_domain' ),
'search_items' => __( 'Search Items', 'text_domain' ),
'not_found' => __( 'Not Found', 'text_domain' ),
'no_terms' => __( 'No items', 'text_domain' ),
'items_list' => __( 'Items list', 'text_domain' ),
'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
'parent_item' => null,
'parent_item_colon' => null,
);
register_taxonomy( 'brands', array( 'product' ), $args );
}
add_action( 'init', 'custom_taxonomy', 0 );
Reference: https://codex.wordpress.org/Function_Reference/register_taxonomy
This will work with WordPress 5.4.2. For me all other solutions show the fields as long as jQuery removes them. My quick and dirty solution hides via CSS and remove them with jQuery. Unfortunately only hiding (not removing) seems to work with Gutenberg Editor. Maybe someone else has another solution.
function remove_tax_parent_dropdown() {
$screen = get_current_screen();
if ( 'category' == $screen->taxonomy ) {
if ( 'edit-tags' == $screen->base ) {
$parent = "$('label[for=parent]').parent().remove(); ";
$css = ".term-parent-wrap{display:none;}";
} elseif ( 'term' == $screen->base ) {
$parent = "$('label[for=parent]').parent().parent().remove(); ";
$css = ".term-parent-wrap{display:none;}";
}
} elseif ( 'post' == $screen->post_type ) {
$parent = "$('#newcategory_parent').remove();";
$css = "div.components-base-control:nth-child(3){display:none;}";
} else {
return;
}
if(!empty($css)) {
echo '<style type="text/css">';
echo $css;
echo '</style>';
}
if(!empty($parent)) {
echo '<script type="text/javascript">';
echo 'jQuery(document).ready(function($) {';
echo $parent;
echo '});';
echo '</script>';
}
}
add_action( 'admin_head-edit-tags.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-term.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-post.php', 'remove_tax_parent_dropdown' );
add_action( 'admin_head-post-new.php', 'remove_tax_parent_dropdown' );
Ah by the way - DON'T use the following code because you get bad issues with it. When you are saving a post without changing category, all categories of this post will be deleted and the category IDs will be created as new categories and added to your post.
global $wp_taxonomies;
$wp_taxonomies['category']->hierarchical = false;

WordPress Custom Post Type Pagination Issue

Both me and my friend are completely bamboozled as to whats going on here. The quest is to have standard pagination linking from one post to the next. We can see the pages going from page/2/, page/3/ etc but the content does not change.
Here is what we've got in the custom template.
<?php
/**
* The Template for displaying all single posts.
*
* Template Name: Portfolio
*
* #package WordPress
* #subpackage Boilerplate
* #since Boilerplate 1.0
*/
get_header();
// Enable Pagination
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => array(
'portfolio'
),
'orderby' => 'date',
'posts_per_page' => 1,
'paged'=>$paged
);
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<article id="item<?php the_ID(); ?>" <?php post_class('post portfolio'); ?>>
<h2><?php the_title(); ?></h2>
<div>
<?php the_content(); ?>
</div>
</article>
<?php endwhile; ?>
<?php next_posts_link('« Older Entries') ?>
<?php previous_posts_link('Newer Entries »') ?>
<?php wp_reset_postdata(); ?>
<?php get_footer(); ?>
And in the bottom of the functions.php lives some custom post type script...
// Custom Post Type
function foggin_Portfolio() {
$labels = array(
'name' => _x( 'Portfolio', 'post type general name' ),
'singular_name' => _x( 'Portfolio', 'post type singular name' ),
'add_new' => _x( 'Add New', 'book' ),
'add_new_item' => __( 'Add New Item' ),
'edit_item' => __( 'Edit item' ),
'new_item' => __( 'New Item' ),
'all_items' => __( 'All Items' ),
'view_item' => __( 'View Item' ),
'search_items' => __( 'Search items' ),
'not_found' => __( 'No item' ),
'not_found_in_trash' => __( 'No items found in the Trash' ),
'parent_item_colon' => '',
'menu_name' => 'Portfolio'
);
$args = array(
'labels' => $labels,
'description' => 'Holds portfolio items and portfolio specific data',
'public' => true,
'menu_position' => 5,
'rewrite' => array('slug'=>'','with_front'=>false),
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields', 'taxonomies'),
'taxonomies' => array('post_tag'),
'has_archive' => true,
);
register_post_type( 'portfolio', $args );
}
add_action( 'init', 'foggin_Portfolio' );
function portfolio_messages( $messages ) {
global $post, $post_ID;
$messages['portfolio'] = array(
0 => '',
1 => sprintf( __('Portfolio item updated. View item'), esc_url( get_permalink($post_ID) ) ),
2 => __('Custom field updated.'),
3 => __('Custom field deleted.'),
4 => __('Product updated.'),
5 => isset($_GET['revision']) ? sprintf( __('Portfolio item restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
6 => sprintf( __('Portfolio item published. View item'), esc_url( get_permalink($post_ID) ) ),
7 => __('Portfolio item saved.'),
8 => sprintf( __('Portfolio item submitted. <a target="_blank" href="%s">Preview item</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
9 => sprintf( __('Portfolio item scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview item</a>'), date_i18n( __( 'M j, Y # G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
10 => sprintf( __('Portfolio item draft updated. <a target="_blank" href="%s">Preview item</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
);
return $messages;
}
add_filter( 'post_updated_messages', 'portfolio_messages' );
function portfolio_taxonomies() {
$labels = array(
'name' => _x( 'Categories', 'taxonomy general name' ),
'singular_name' => _x( 'Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Categories' ),
'all_items' => __( 'All Categories' ),
'parent_item' => __( 'Parent Category' ),
'parent_item_colon' => __( 'Parent Category:' ),
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category' ),
'menu_name' => __( 'Categories' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
);
register_taxonomy( 'portfolio_category', 'portfolio', $args );
}
add_action( 'init', 'portfolio_taxonomies', 0 );
?>
Thoughts, ideas, advice would be really helpful I think it's fair to say we're both stumped on this.
It may sound silly, but reset your permalinks to default, then back to your desired format. The .htaccess file needs to be rewritten after the post types have been added into functions.php
Your action for rewrite option being set to false could be causing an issue as well. If WP isn't clear on rewriting yourdomain.com/page/2/ so having the rewrite to true makes it yourdomain.com/portfolio/page/2/
Everything else seems to be in order with your query.

Resources