WP custom_pre_get_posts breaks theme - php

I added this code weeks ago, but it suddenly stopped working last night, how could that be? It works fine on a local server, but not on a shared host. Local is running PHP 5.5.3 and host was running 5.4, but I put in a request to upgrade that specific subdomain to 5.5 just now in case that was at play.
Working with a child theme. The parent theme creates a custom post type called Portfolio, with the slug for all posts in it as /portfolio-item/. In my child theme, I added two things: 1. A new custom post type called Hidden Pages, and I used a code I found online that removes the slug, so it's just domain.com/page-name. 2. I added more code referring to the Portfolio type, which also removes the slug.
Everything was working perfectly, but all of a sudden, all standard pages 404 (and are hidden on the backend, but not in the database, this is not a database problem!), and the Portfolio posts are magically moved to the blog (regular standard posts). If you comment out the custom_pre_get_posts line (132), the problem resolves. But the client needs the urls to be clean without the slug. So I do not want to leave it as-is.
Here is the functions.php for the child theme:
<?php
function evol_child_scripts() {
wp_enqueue_style( 'style', get_stylesheet_directory_uri() . '/stylesheets/css/style.css' );
}
add_action( 'wp_enqueue_scripts', 'evol_child_scripts' );
/*function codex_custom_init() {
$args = array(
'public' => true,
'label' => 'Hidden Pages'
);
register_post_type( 'hidden', $args );
}
add_action( 'init', 'codex_custom_init' );
*/
/**
* Register a custom post type but don't do anything fancy
*/
register_post_type( 'hidden', array( 'label' => 'Hidden Pages', 'public' => true, 'capability_type' => 'post', 'show_ui' => true, 'query_var' => true, 'supports' => array( 'title', 'editor', 'thumbnail' ) ) );
/**
* Remove the slug from published post permalinks. Only affect our CPT though.
*/
function vipx_remove_cpt_slug( $post_link, $post, $leavename ) {
if ( ! in_array( $post->post_type, array( 'hidden' ) )
|| 'publish' != $post->post_status )
return $post_link;
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'vipx_remove_cpt_slug', 10, 3 );
/**
* Some hackery to have WordPress match postname to any of our public
* post types. All of our public post types can have /post-name/ as
* the slug, so they better be unique across all posts. Typically core
* only accounts for posts and pages where the slug is /post-name/
*/
function vipx_parse_request_tricksy( $query ) {
// Only noop the main query
if ( ! $query->is_main_query() )
return;
// Only noop our very specific rewrite rule match
if ( 2 != count( $query->query )
|| ! isset( $query->query['page'] ) )
return;
// 'name' will be set if post permalinks are just post_name,
// otherwise the page rule will match
if ( ! empty( $query->query['name'] ) )
$query->set( 'post_type', array( 'post', 'hidden', 'page' ) );
}
add_action( 'pre_get_posts', 'vipx_parse_request_tricksy' );
function remove_search_filter () {
remove_filter( 'pre_get_posts', 'tr_search_filter' );
}
add_action( 'init', 'remove_search_filter');
function remove_icons() {
wp_dequeue_style( 'icons' );
}
add_action( 'wp_enqueue_scripts', 'remove_icons' );
function tr_widgets_init_2() {
if ( ot_get_option( 'tr_sidebars' ) ) :
$tr_sidebars = ot_get_option( 'tr_sidebars' );
foreach ( $tr_sidebars as $tr_sidebar ) {
register_sidebar( array(
'id' => $tr_sidebar["id"],
'name' => $tr_sidebar["title"],
'before_widget' => '<div class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h6 class="widget-title">',
'after_title' => '</h6>',
));
}
endif;
};
add_action( 'widgets_init', 'tr_widgets_init_2' );
add_filter('post_type_link','custom_post_type_link', 10, 3);
function custom_post_type_link($permalink, $post, $leavename) {
$url_components = parse_url($permalink);
$post_path = $url_components['path'];
$post_name = end((explode('/', trim($post_path, '/'))));
if(!empty($post_name)) {
switch($post->post_type) {
case 'portfolio':
$permalink = str_replace($post_path, '/' . $post_name . '/', $permalink);
break;
}
}
return $permalink;
}
function custom_pre_get_posts($query) {
global $wpdb;
if(!$query->is_main_query()) {
return;
}
$post_name = $query->get('name');
$post_type = $wpdb->get_var( $wpdb->prepare( 'SELECT post_type FROM ' . $wpdb->posts . ' WHERE post_name = %s LIMIT 1', $post_name ) );
switch($post_type) {
case 'portfolio':
$query->set('portfolio', $post_name);
$query->set('post_type', $post_type);
$query->is_single = true;
$query->is_page = false;
break;
}
return $query;
}
add_action('pre_get_posts','custom_pre_get_posts');
function fb_add_search_box ( $items, $args ) {
// only on primary menu
if( 'primary' === $args -> theme_location )
$items .= '<li class="menu-item menu-item-search">' . get_search_form( FALSE ) . '</li>';
return $items;
}
add_filter( 'wp_nav_menu_items', 'fb_add_search_box', 10, 2 );
// Callback function to insert 'styleselect' into the $buttons array
function my_mce_buttons_2( $buttons ) {
array_unshift( $buttons, 'styleselect' );
return $buttons;
}
// Register our callback to the appropriate filter
add_filter('mce_buttons_2', 'my_mce_buttons_2');
// Callback function to filter the MCE settings
function my_mce_before_init_insert_formats( $init_array ) {
// Define the style_formats array
$style_formats = array(
// Each array child is a format with it's own settings
array(
'title' => 'Image Text',
'block' => 'p',
'classes' => 'image-text',
),
array(
'title' => 'Image Text no Overlay',
'block' => 'p',
'classes' => 'image-text-2',
),
array(
'title' => 'w/ gray background',
'inline' => 'span',
'exact' => true,
'classes' => 'gray-background',
),
array(
'title' => 'w/ white background',
'inline' => 'span',
'exact' => true,
'classes' => 'white-background',
),
array(
'title' => 'Image Text no Indent',
'block' => 'p',
'classes' => 'image-text-3',
),
array(
'title' => 'Button',
'inline' => 'a',
'exact' => true,
'classes' => 'button small',
),
array(
'title' => 'Blog Image Caption',
'block' => 'p',
'classes' => 'caption',
),
array(
'title' => 'Signature',
'inline' => 'span',
'exact' => true,
'classes' => 'sign',
),
);
// Insert the array, JSON ENCODED, into 'style_formats'
$init_array['style_formats'] = json_encode( $style_formats );
return $init_array;
}
// Attach callback to 'tiny_mce_before_init'
add_filter( 'tiny_mce_before_init', 'my_mce_before_init_insert_formats' );
This is the parent functions.php:
<?php
/*----------------------------------------------------------------------------*/
/* Sets up theme defaults and registers support for various WordPress features.
/*----------------------------------------------------------------------------*/
function tr_theme_setup() {
load_theme_textdomain( 'themerain', get_template_directory() . '/languages' );
add_theme_support( 'automatic-feed-links' );
add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list' ) );
register_nav_menu( 'primary', 'Navigation Menu' );
add_theme_support( 'post-thumbnails' );
add_image_size( 'portfolio', 740, 540, true );
}
add_action( 'after_setup_theme', 'tr_theme_setup' );
/*----------------------------------------------------------------------------*/
/* Sets up the content width value based on the theme's design and stylesheet.
/*----------------------------------------------------------------------------*/
if ( ! isset( $content_width ) ) $content_width = 780;
/*----------------------------------------------------------------------------*/
/* Load Theme Options
/*----------------------------------------------------------------------------*/
add_filter( 'ot_show_pages', '__return_false' );
add_filter( 'ot_show_new_layout', '__return_false' );
add_filter( 'ot_theme_mode', '__return_true' );
load_template( trailingslashit( get_template_directory() ) . 'option-tree/ot-loader.php' );
load_template( trailingslashit( get_template_directory() ) . 'includes/theme-options.php' );
load_template( trailingslashit( get_template_directory() ) . 'includes/meta-boxes.php' );
load_template( trailingslashit( get_template_directory() ) . 'includes/theme-functions.php' );
/*----------------------------------------------------------------------------*/
/* Register Sidebars
/*----------------------------------------------------------------------------*/
function tr_widgets_init() {
register_sidebar( array(
'id' => 'sidebar',
'name' => 'Default Sidebar',
'before_widget' => '<div class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h6 class="widget-title">',
'after_title' => '</h6>',
));
register_sidebar( array(
'id' => 'footer-sidebar',
'name' => 'Footer Sidebar',
'before_widget' => '<div class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h6 class="widget-title">',
'after_title' => '</h6>',
));
if ( ot_get_option( 'tr_sidebars' ) ) :
$tr_sidebars = ot_get_option( 'tr_sidebars' );
foreach ( $tr_sidebars as $tr_sidebar ) {
register_sidebar( array(
'id' => $tr_sidebar["id"],
'name' => $tr_sidebar["title"],
'before_widget' => '<div class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h6 class="widget-title">',
'after_title' => '</h6>',
));
}
endif;
};
add_action( 'widgets_init', 'tr_widgets_init' );
/*----------------------------------------------------------------------------*/
/* Register and load CSS & jQuery
/*----------------------------------------------------------------------------*/
function tr_enqueue_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
wp_enqueue_style( 'icons', get_template_directory_uri() . '/assets/css/icons.css' );
wp_enqueue_style( 'magnific', get_template_directory_uri() . '/assets/css/magnific-popup.css' );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'custom', get_template_directory_uri() . '/assets/js/jquery.custom.js', 'jquery' );
wp_enqueue_script( 'flexslider', get_template_directory_uri() . '/assets/js/jquery.flexslider.min.js', 'jquery' );
wp_enqueue_script( 'isotope', get_template_directory_uri() . '/assets/js/jquery.isotope.min.js', 'jquery' );
wp_enqueue_script( 'magnific', get_template_directory_uri() . '/assets/js/jquery.magnific-popup.min.js', 'jquery' );
wp_enqueue_script( 'validation', get_template_directory_uri() . '/assets/js/jquery.validate.min.js', 'jquery' );
if ( is_singular() ) wp_enqueue_script( 'comment-reply' );
}
add_action( 'wp_enqueue_scripts', 'tr_enqueue_scripts' );
/*----------------------------------------------------------------------------*/
/* Load Widgets
/*----------------------------------------------------------------------------*/
include( "includes/widget-recent-projects.php" );
/*----------------------------------------------------------------------------*/
/* Configure Pagination
/*----------------------------------------------------------------------------*/
function tr_pagination() {
global $wp_query, $wp_rewrite;
$pages = '';
$total = 1;
$max = $wp_query->max_num_pages;
if ( ! $current = get_query_var( 'paged' ) ) $current = 1;
$args['base'] = str_replace( 999999999, '%#%', get_pagenum_link( 999999999 ) );
$args['total'] = $max;
$args['current'] = $current;
$args['end_size'] = 1;
$args['mid_size'] = 3;
$args['prev_text'] = '<i class="fa-angle-left"></i> Previous';
$args['next_text'] = 'Next <i class="fa-angle-right"></i>';
$args['type'] = 'list';
if ( $max > 1 ) echo '<div id="pagination">';
if ( $total == 1 && $max > 1 );
echo $pages . paginate_links( $args );
if ( $max > 1 ) echo '</div>';
}
/*----------------------------------------------------------------------------*/
/* Configure Excerpt
/*----------------------------------------------------------------------------*/
function new_excerpt_more( $more ) {
return ' ...';
}
add_filter( 'excerpt_more', 'new_excerpt_more' );
/*-----------------------------------------------------------------------------------*/
/* Configure Tag Cloud
/*-----------------------------------------------------------------------------------*/
function tag_cloud_filter($args = array()) {
$args['smallest'] = 12;
$args['largest'] = 12;
$args['unit'] = 'px';
return $args;
}
add_filter('widget_tag_cloud_args', 'tag_cloud_filter', 90);
/*----------------------------------------------------------------------------*/
/* Exclude Pages from Search
/*----------------------------------------------------------------------------*/
function tr_search_filter( $filter ) {
if ( $filter->is_search ) {
$filter->set( 'post_type', 'post' );
}
return $filter;
}
add_filter( 'pre_get_posts', 'tr_search_filter' );
/*----------------------------------------------------------------------------*/
/* Add Portfolio Post Types
/*----------------------------------------------------------------------------*/
function tr_portfolio() {
$labels = array(
'name' => 'Portfolio',
'singular_name' => 'Portfolio Item',
'add_new' => 'Add New',
'add_new_item' => 'Add New Portfolio Item',
'edit_item' => 'Edit Portfolio Item',
'new_item' => 'New Portfolio Items',
'view_item' => 'View Portfolio Item',
'search_items' => 'Search Portfolio Items',
'not_found' => 'No Portfolio Items found',
'not_found_in_trash' => 'No Portfolio Items found in Trash',
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 4,
'rewrite' => array( 'slug' => 'portfolio-item' ),
'supports' => array( 'title', 'editor', 'thumbnail' )
);
register_post_type( 'portfolio', $args );
register_taxonomy(
"portfolio-category", array( "portfolio" ), array(
"hierarchical" => true,
"label" => "Portfolio Categories",
"singular_label" => "Portfolio Categories",
"rewrite" => true,
"query_var" => true
)
);
}
add_action( 'init', 'tr_portfolio' );
/*----------------------------------------------------------------------------*/
/* Add Gallery Post Types
/*----------------------------------------------------------------------------*/
function tr_gallery() {
$labels = array(
'name' => 'Gallery',
'singular_name' => 'Gallery Item',
'add_new' => 'Add New',
'add_new_item' => 'Add New Gallery Item',
'edit_item' => 'Edit Gallery Item',
'new_item' => 'New Gallery Items',
'view_item' => 'View Gallery Item',
'search_items' => 'Search Gallery Items',
'not_found' => 'No Gallery Items found',
'not_found_in_trash' => 'No Gallery Items found in Trash',
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 4,
'rewrite' => array( 'slug' => 'gallery-item' ),
'supports' => array( 'title', 'thumbnail' )
);
register_post_type( 'gallery', $args );
register_taxonomy(
"gallery-category", array( "gallery" ), array(
"hierarchical" => true,
"label" => "Gallery Categories",
"singular_label" => "Gallery Categories",
"rewrite" => true,
"query_var" => true
)
);
}
add_action( 'init', 'tr_gallery' );
/*----------------------------------------------------------------------------*/
/* Add a Custom Taxonomy to the Post Class
/*----------------------------------------------------------------------------*/
function custom_portfolio_post_class( $classes, $class, $ID ) {
$taxonomy = 'portfolio-category';
$terms = get_the_terms( (int) $ID, $taxonomy );
if ( ! empty( $terms ) ) {
foreach ( (array) $terms as $order => $term ) {
if ( ! in_array( $term->slug, $classes ) ) {
$classes[] = $term->slug;
}
}
}
return $classes;
}
add_filter( 'post_class', 'custom_portfolio_post_class', 10, 3 );
function custom_gallery_post_class( $classes, $class, $ID ) {
$taxonomy = 'gallery-category';
$terms = get_the_terms( (int) $ID, $taxonomy );
if ( ! empty( $terms ) ) {
foreach ( (array) $terms as $order => $term ) {
if ( ! in_array( $term->slug, $classes ) ) {
$classes[] = $term->slug;
}
}
}
return $classes;
}
add_filter( 'post_class', 'custom_gallery_post_class', 10, 3 );
/*----------------------------------------------------------------------------*/
/* Register the Required Plugins
/*----------------------------------------------------------------------------*/
require_once dirname( __FILE__ ) . '/includes/plugin-activation.php';
function tr_register_required_plugins() {
$plugins = array(
array(
'name' => 'Rain Shortcodes',
'slug' => 'rain-shortcodes',
'source' => get_stylesheet_directory() . '/includes/plugins/rain-shortcodes.zip',
'required' => true,
'version' => '',
'force_activation' => false,
'force_deactivation' => false,
'external_url' => '',
)
);
$theme_text_domain = 'tgmpa';
$config = array(
'domain' => $theme_text_domain,
'default_path' => '',
'parent_menu_slug' => 'themes.php',
'parent_url_slug' => 'themes.php',
'menu' => 'install-required-plugins',
'has_notices' => true,
'is_automatic' => true,
'message' => '',
'strings' => array(
'page_title' => __( 'Install Required Plugins', $theme_text_domain ),
'menu_title' => __( 'Install Plugins', $theme_text_domain ),
'installing' => __( 'Installing Plugin: %s', $theme_text_domain ), // %1$s = plugin name
'oops' => __( 'Something went wrong with the plugin API.', $theme_text_domain ),
'notice_can_install_required' => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.' ),
'notice_can_install_recommended' => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.' ),
'notice_cannot_install' => _n_noop( 'Sorry, but you do not have the correct permissions to install the %s plugin. Contact the administrator of this site for help on getting the plugin installed.', 'Sorry, but you do not have the correct permissions to install the %s plugins. Contact the administrator of this site for help on getting the plugins installed.' ),
'notice_can_activate_required' => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.' ),
'notice_can_activate_recommended' => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.' ),
'notice_cannot_activate' => _n_noop( 'Sorry, but you do not have the correct permissions to activate the %s plugin. Contact the administrator of this site for help on getting the plugin activated.', 'Sorry, but you do not have the correct permissions to activate the %s plugins. Contact the administrator of this site for help on getting the plugins activated.' ),
'notice_ask_to_update' => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.' ),
'notice_cannot_update' => _n_noop( 'Sorry, but you do not have the correct permissions to update the %s plugin. Contact the administrator of this site for help on getting the plugin updated.', 'Sorry, but you do not have the correct permissions to update the %s plugins. Contact the administrator of this site for help on getting the plugins updated.' ),
'install_link' => _n_noop( 'Begin installing plugin', 'Begin installing plugins' ),
'activate_link' => _n_noop( 'Activate installed plugin', 'Activate installed plugins' ),
'return' => __( 'Return to Required Plugins Installer', $theme_text_domain ),
'plugin_activated' => __( 'Plugin activated successfully.', $theme_text_domain ),
'complete' => __( 'All plugins installed and activated successfully. %s', $theme_text_domain ),
'nag_type' => 'updated'
)
);
tgmpa( $plugins, $config );
}
add_action( 'tgmpa_register', 'tr_register_required_plugins' );
?>
When wp_debug is set to true, this returns:
Strict Standards: Only variables should be passed by reference in
[path redacted]/functions.php on line 97
This refers to this line:
$post_name = end(explode('/', trim($post_path, '/')));
This is still in the error log, but after a change, it is not there on the admin side, does that mean it's fixed?
Child theme code is from here: https://gist.github.com/stefanbc/6620151 and http://www.markwarddesign.com/2014/02/remove-custom-post-type-slug-permalink/
So, if anyone knows how to modify this file to revert everything back to working perfectly, that'd be great. We are days away from launch, actually. Eep. Thank you!

Problem is not with Wordpress as the error stated, It's all pure PHP. You should make a little change in that line (wrapping explode() with parenthesis):
$post_name = end((explode('/', trim($post_path, '/'))));

I could not find a solution to this problem given my level of PHP and not wanting to rewrite code that involves both a parent and child theme's functions. I ended up removing all code that attempted to remove the slug. I crossed my fingers and installed this outdated plugin and it worked. So for anyone for future reference, I suppose you can avoid code and just use this instead!
https://wordpress.org/plugins/remove-slug-from-custom-post-type/

Related

How to display cpt categories in sidebar?

I want to display my cpt categories in sidebar of cpt, my codes as as follows
//add custom menus
function codex_custom_init() {
register_post_type(
'Jobs', array(
'labels' => array('name' => __( 'Jobs' ), 'singular_name' => __( 'Jobs' ) ),
'public' => true,
'has_archive' => true,
'supports' => array('title', 'editor', 'thumbnail'),
'menu_icon' => 'dashicons-calendar-alt',
'show_in_rest' => 'true'
)
);
}
add_action( 'init', 'codex_custom_init' );
function jobs_create_my_taxonomy() {
register_taxonomy(
'jobs-category',
'jobs',
array(
'label' => __( 'Category' ),
'rewrite' => array( 'slug' => 'jobs-category' ),
'hierarchical' => true,
'show_in_rest' => 'true'
)
);
}
add_action( 'init', 'jobs_create_my_taxonomy' );
I need to display cpt categories in sidebar with category links.
You can use add_shortcode and get_terms. add show_category to sidebar.
function show_category(){
$jobs_category = get_terms( array(
'taxonomy' => 'jobs-category',
'hide_empty' => false
) );
if ( !empty( $jobs_category ) ) {
$output = '<ul>';
foreach( $jobs_category as $category ) {
$output.= '<li>'. esc_attr( $category->name ) .'</li>';
}
$output.= '</ul>';
echo $output;
}
}
add_shortcode( 'show_category', 'show_category' );

How can I unregister this custom post type?

I'm using a theme that has a Testimonials CPT that I don't need. I'm trying to unregister it but my code isn't working.
Here is the code from the theme that registers the CPT.
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class Testimonial_CPT {
protected $textdomain;
protected $posts;
protected $version;
public function __construct( $textdomain ) {
// Initialize variables
global $wp_version;
$this->version = $wp_version;
$this->textdomain = $textdomain;
$this->posts = array();
// Add the action hooks
add_action( 'init', array( &$this, 'register_testimonials' ) ); // Register Associated Taxonomy
if( $this->version >= 3.8 ) {
add_action( 'admin_head', array( &$this, 'add_menu_icons_styles' ) ); // Add icon if WP =< 3.8
}
add_action( 'after_switch_theme', array( &$this, 'custom_flush_rules' ) ); // Flush rewrite rules
}
public function testimonial_init() {
// Define the settings
$settings = array(
'labels' => array(
'name' => __( 'Testimonials', $this->textdomain),
'menu_name' => __( 'Testimonials', $this->textdomain),
'singular_name' => __( 'Testimonial', $this->textdomain),
'all_items' => __( 'All Testimonials', $this->textdomain),
'add_new' => __( 'Add New', $this->textdomain ),
'add_new_item' => __( 'Add New Testimonial', $this->textdomain ),
'edit_item' => __( 'Edit Testimonial', $this->textdomain ),
'new_item' => __( 'New Testimonial', $this->textdomain ),
'view_item' => __( 'View Testimonial', $this->textdomain ),
'search_items' => __( 'Search Testimonials', $this->textdomain ),
'not_found' => __( 'No testimonials found', $this->textdomain ),
'not_found_in_trash' => __( 'No testimonials found in Trash', $this->textdomain )
),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => false,
'menu_position ' => null,
'menu_icon' => get_template_directory_uri(). '/images/user-icon.png',
'supports' => array( 'title', 'editor', 'thumbnail', 'revisions' ),
'hierarchical' => false,
'has_archive' => true,
'rewrite' => array(
'slug' => 'testimonial'
)
); // End $settings
// Conditional to set the icon if WP 3.8 <
if( $this->version >= 3.8 ) {
$settings['menu_icon'] = '';
}
// Store the settings in the post array
$this->posts['testimonial'] = $settings;
}
public function register_testimonials() {
// Loop through the registered posts
// and register all posts stored in the array
foreach( $this->posts as $key=>$value ) {
register_post_type( $key, $value );
}
}
public function add_menu_icons_styles() {
?>
<style>
#adminmenu .menu-icon-testimonial div.wp-menu-image:before { content: '\f110'; }
</style>
<?php
}
// Flush Rules
public function custom_flush_rules(){
//defines the post type so the rules can be flushed.
$this->register_testimonials();
//and flush the rules.
flush_rewrite_rules();
}
} // End Testimonial_CPT
?>
And here is the code I'm using to unregister it.
add_action('init','delete_post_type', 100);
function delete_post_type(){
unregister_post_type( 'testimonials' );
}
I got the code directly from the WordPress Codex. Any idea where I'm going wrong?
/**
* Remove testimonial CPT
*/
function remove_testimonial_cpt() {
unregister_post_type( 'testimonial' );
}
add_action( 'init', 'remove_testimonial_cpt', 1000 );
Copy this code and paste it into your functions.php file of child themes
Important link:
unregister_post_type we have a function to remove register CPT from websites

Wordpress shows random output beginning with flush_rules();

I already think I know the problem, there is a <?php somewhere or somewhere there is written <? and it makes the site crash but I don't know where it is.
Now I don't ask you to look through the whole code but if you know where I would find this if this ever happened to you.
So I migrated the site from cpanel to a new self managed server. (runcloud "on top off" digital ocean)
But after the migration it shows this kind of output.
Thanks for taking your time to answer this question.
I already searched for the same question but I don't seem to find the same problem.
`flush_rules(); //regestering menu register_nav_menus(array( 'top_menu'=>'Top navigation' ,'main_menu' => 'Main navigation' ,'inner_menu' => 'Inner navigation')); //add thumnails support if (function_exists('add_theme_support')){ add_theme_support('post-thumbnails'); } //disable auto image link function setup_default_image_link() { $original_setting = get_option( 'image_default_link'); if ($original_setting !== 'none') { update_option('image_default_link_type', 'none'); } } add_action('admin_init', 'setup_default_image_link', 50); update_option('image_default_link_type', 'none'); //remove P around images function filter_ptags_on_images($content){ return preg_replace('/
\s*()?\s*()\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content); } add_filter('the_content', 'filter_ptags_on_images'); //add support of page attributes add_post_type_support( 'post', 'page-attributes' ); /* * Switch default core markup for search form, comment form, and comments * to output valid HTML5. */ add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption' ) ); //add custom header with image or video /* //image add_theme_support( 'custom-header' ); //video add_theme_support( 'custom-header', array( 'video' => true, ) ); /**/ //add_theme_support( 'selective-refresh' ); add_theme_support( 'customize-selective-refresh-widgets' ); /* auto-detect the server so you only have to enter the front/from half of the email address, including the # sign */ /** function xyz_filter_wp_mail_from($email){ $sitename = strtolower( $_SERVER['SERVER_NAME'] ); if ( substr( $sitename, 0, 4 ) == 'www.' ) { $sitename = substr( $sitename, 4 ); } $myfront = "noreply#"; $myback = $sitename; $myfrom = $myfront . $myback; return $myfrom; } add_filter("wp_mail_from", "xyz_filter_wp_mail_from"); function xyz_filter_wp_mail_from_name($from_name){ $sitename = strtolower( $_SERVER['SERVER_NAME'] ); if ( substr( $sitename, 0, 4 ) == 'www.' ) { $sitename = substr( $sitename, 4 ); } return $sitename; } add_filter("wp_mail_from_name", "xyz_filter_wp_mail_from_name"); /**/ //remove footer add_filter( 'admin_footer_text', '__return_empty_string', 11 ); add_filter( 'update_footer', '__return_empty_string', 11 ); //remove Category, Archive, etc. from title add_filter( 'get_the_archive_title', function ($title) { if ( is_category() ) { $title = sprintf( __( '%s' ), single_cat_title( '', false ) ); } elseif ( is_tag() ) { $title = sprintf( __( '%s' ), single_tag_title( '', false ) ); } elseif ( is_author() ) { $title = sprintf( __( '%s' ), '' . get_the_author() . '' ); } elseif ( is_year() ) { $title = sprintf( __( '%s' ), get_the_date( _x( 'Y', 'yearly archives date format' ) ) ); } elseif ( is_month() ) { $title = sprintf( __( '%s' ), get_the_date( _x( 'F Y', 'monthly archives date format' ) ) ); } elseif ( is_day() ) { $title = sprintf( __( '%s' ), get_the_date( _x( 'F j, Y', 'daily archives date format' ) ) ); } elseif ( is_tax( 'post_format' ) ) { if ( is_tax( 'post_format', 'post-format-aside' ) ) { $title = _x( '', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-gallery' ) ) { $title = _x( '', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-image' ) ) { $title = _x( '', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-video' ) ) { $title = _x( '', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-quote' ) ) { $title = _x( '', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-link' ) ) { $title = _x( '', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-status' ) ) { $title = _x( '', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-audio' ) ) { $title = _x( '', 'post format archive title' ); } elseif ( is_tax( 'post_format', 'post-format-chat' ) ) { $title = _x( '', 'post format archive title' ); } } elseif ( is_post_type_archive() ) { $title = sprintf( __( '%s' ), post_type_archive_title( '', false ) ); } elseif ( is_tax() ) { $tax = get_taxonomy( get_queried_object()->taxonomy ); $title = sprintf( __( '%1$s: %2$s' ), $tax->labels->singular_name, single_term_title( '', false ) ); } else { $title = __( '' ); } return $title; }); //set count of posts on custom archive page function set_posts_per_page_for_towns_cpt( $query ) { if ( !is_admin() && $query->is_main_query() && is_post_type_archive( 'news' ) || is_tax( 'news_categories' ) ) { $query->set( 'posts_per_page', '6' ); }elseif ( !is_admin() && $query->is_main_query() && is_post_type_archive( 'our_work' ) ) { $query->set( 'posts_per_page', '6' ); } } add_action( 'pre_get_posts', 'set_posts_per_page_for_towns_cpt' ); function remove_menus(){ remove_menu_page( 'edit.php' ); //Posts http://sw/wp-admin/ // remove_menu_page( 'index.php' ); //Dashboard // remove_menu_page( 'jetpack' ); //Jetpack* // remove_menu_page( 'upload.php' ); //Media // remove_menu_page( 'edit.php?post_type=page' ); //Pages // remove_menu_page( 'edit-comments.php' ); //Comments // remove_menu_page( 'themes.php' ); //Appearance // remove_menu_page( 'plugins.php' ); //Plugins // remove_menu_page( 'users.php' ); //Users // remove_menu_page( 'tools.php' ); //Tools // remove_menu_page( 'options-general.php' ); //Settings } add_action( 'admin_menu', 'remove_menus' ); //add tiny mce templates add_filter( 'tinymce_templates_enable_media_buttons', function(){ return true; }); function change_wp_search_size($query) { if ( $query->is_search){ // Make sure it is a search page $query->query_vars['posts_per_page'] = -1; // Change 10 to the number of posts you would like to show //$query->set('post_type',array('publications')); } return $query; // Return our modified query variables } //add_filter('pre_get_posts', 'change_wp_search_size'); ?> array( 'name' => 'News', 'all_items' => 'All News' ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'news'), 'supports' => array('title'), 'exclude_from_search' => false )); register_post_type('events', array( 'labels' => array( 'name' => 'Events', 'all_items' => 'All Events' ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'events'), 'supports' => array('title'), 'exclude_from_search' => false )); register_post_type('publications', array( 'labels' => array( 'name' => 'Publications', 'all_items' => 'All Publications' ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'publications'), 'supports' => array('title'), 'exclude_from_search' => false )); register_post_type('our_work', array( 'labels' => array( 'name' => 'Our Work', 'all_items' => 'All Work' ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'our-work'), 'supports' => array('title'), 'exclude_from_search' => false )); register_post_type('members', array( 'labels' => array( 'name' => 'Our Members', 'all_items' => 'All Members' ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'members'), 'supports' => array('title'), 'exclude_from_search' => false )); } add_action('init', 'create_post_types'); // register Taxonomies function create_taxonomies() { register_taxonomy('news_categories', array('news'), array( 'labels' => array( 'name' => 'News Categories' ), 'show_ui' => true, 'show_tagcloud' => false, 'hierarchical' => true, 'rewrite' => array( 'slug' => 'news' ) )); register_taxonomy('publications_categories', array('publications'), array( 'labels' => array( 'name' => 'Publications Categories' ), 'show_ui' => true, 'show_tagcloud' => false, 'hierarchical' => true, 'rewrite' => array( 'slug' => 'publications' ) )); register_taxonomy('members_categories', array('members'), array( 'labels' => array( 'name' => 'Members Categories' ), 'show_ui' => true, 'show_tagcloud' => false, 'hierarchical' => true, 'rewrite' => array( 'slug' => 'members' ) )); } add_action('init', 'create_taxonomies'); // rewrite urls function taxonomy_slug_rewrite($wp_rewrite) { $rules = array(); $taxonomies = get_taxonomies(array('_builtin' => false), 'objects'); $post_types = get_post_types(array('public' => true, '_builtin' => false), 'names'); foreach ($post_types as $post_type) { foreach ($taxonomies as $taxonomy) { if ($taxonomy->object_type[0] == $post_type) { $categories = get_categories(array('type' => $post_type, 'taxonomy' => $taxonomy->name, 'hide_empty' => 0)); foreach ($categories as $category) { $rules[$post_type . '/' . $category->slug . '/?$'] = 'index.php?' . $category->taxonomy . '=' . $category->slug; } } } } $wp_rewrite->rules = $rules + $wp_rewrite->rules; } add_filter( 'generate_rewrite_rules', 'taxonomy_slug_rewrite' ); ?> $user_id, 'admin_color' => 'custom' ); wp_update_user( $args ); } add_action('user_register', 'set_default_admin_color'); if(get_current_user_id() != 1){ remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' ); } ?> admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce('myajax-nonce'))); //wp_localize_script('plugins', 'WPURLS', array( 'siteurl' => get_bloginfo("template_url") )); //wp_register_script( 'retina', get_template_directory_uri() . '/assets/js/libs/retina.min.js', array( 'backbone' )); wp_enqueue_script( 'custom-script' ); wp_enqueue_script('detect'); wp_enqueue_script('main_scripts'); wp_enqueue_script('plugins'); // wp_enqueue_script('retina'); } add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_jquery' ); //load admin scripts add_action( 'admin_enqueue_scripts', 'load_admin_scripts' ); function load_admin_scripts() { wp_enqueue_script( 'admin_js', get_admin_url() . 'backend/current/js/scripts.js' ); wp_localize_script( 'admin_js', 'backend_path', get_admin_url()); } if (!is_admin()) { //move all scripts to the footer function footer_enqueue_scripts(){ remove_action('wp_head','wp_print_scripts'); remove_action('wp_head','wp_print_head_scripts',9); remove_action('wp_head','wp_enqueue_scripts',1); add_action('wp_footer','wp_print_scripts',5); add_action('wp_footer','wp_enqueue_scripts',5); add_action('wp_footer','wp_print_head_scripts',5); } add_action('after_setup_theme','footer_enqueue_scripts'); } ?> __( 'Footer Main Menu', 'CURRENT WEBSITE' ), // 'id' => 'main_menu_widget', // 'description' => __( '', 'CURRENT WEBSITE' ), // 'before_widget' => '', // 'before_title' => '
', // 'after_title' => '
', // 'after_widget' => '
', // ) ); register_sidebar( array( 'name' => __( 'Facebook', 'CURRENT WEBSITE' ), 'id' => 'facebook_widget', 'description' => __( '', 'CURRENT WEBSITE' ), 'before_widget' => '
', 'before_title' => '
', 'after_title' => '
', 'after_widget' => '
', ) ); register_sidebar( array( 'name' => __( 'Twitter', 'CURRENT WEBSITE' ), 'id' => 'twitter_widget', 'description' => __( '', 'CURRENT WEBSITE' ), 'before_widget' => '', 'before_title' => '
', 'after_title' => '
', 'after_widget' => '
', ) ); register_sidebar( array( 'name' => __( 'Main Section Footer', 'CURRENT WEBSITE' ), 'id' => 'main_section_footer', 'description' => __( '', 'CURRENT WEBSITE' ), 'before_widget' => '
', 'after_widget' => '
', 'before_title' => '
', 'after_title' => '
', ) ); /* register_sidebar( array( 'name' => __( 'Language Switcher', 'CURRENT WEBSITE' ), 'id' => 'language_switcher', 'description' => __( '', 'CURRENT WEBSITE' ), 'before_widget' => '
', 'after_widget' => '
', 'before_title' => '
', 'after_title' => '
', ) ); register_sidebar( array( 'name' => __( 'Main Content Right Sidebar', 'CURRENT WEBSITE' ), 'id' => 'main_content_right_sidebar', 'description' => __( '', 'CURRENT WEBSITE' ), 'before_widget' => '
', 'after_widget' => '
', 'before_title' => '
', 'after_title' => '
', ) ); register_sidebar( array( 'name' => __( 'Main Content Left Sidebar', 'CURRENT WEBSITE' ), 'id' => 'main_content_left_sidebar', 'description' => __( '', 'CURRENT WEBSITE' ), 'before_widget' => '
', 'after_widget' => '
', 'before_title' => '
', 'after_title' => '
', ) ); register_sidebar( array( 'name' => __( 'Footer Right Sidebar', 'CURRENT WEBSITE' ), 'id' => 'footer_right_sidebar', 'description' => __( '', 'CURRENT WEBSITE' ), 'before_widget' => '
', 'after_widget' => '
', 'before_title' => '
', 'after_title' => '
', ) ); register_sidebar( array( 'name' => __( 'Footer Center Content', 'CURRENT WEBSITE' ), 'id' => 'footer_center_content', 'description' => __( '', 'CURRENT WEBSITE' ), 'before_widget' => '
', 'after_widget' => '
', 'before_title' => '
', 'after_title' => '
', ) ); */ } add_action( 'widgets_init', 'my_widgets_init' ); ?>`
If I understood the question correctly, you have some errors in your code but you don't know where exactly those errors are.
In this case you should either:
check your system PHP error log
or turn on WP_DEBUG in your wp-config.php file (see WP docs)
You'll see errors/warnings/notices produced by the PHP engine, and those messages will contain something like ... on line XXX in /some/path/to/some/file.php. This tells you exactly where the error/warning/notice happens. Open that file on that line and fix the issue.

How to change custom post type pemalink Hierarcy

When we set permalink as Post name and go to wordpress any default post Like "Testing 123" single page its link looks like this
localhost/foo_articles/testing-123
Now i when we change our permalink to Custom Structure and set value like %category%/%postname%, the link looks like this
http://localhost/foo_articles/testing/testing-123/
testing is my category slug
Now the main part of my question is
I make a plugin where i create a post type foo_articles and custom taxonomy foo_categories
Its work perfectly. When i click on a category its link looks like this
http://localhost/foo_articles/foo_category/junk-food/
and when i click on an article for a single page, its link looks like this
http://localhost/foo_articles/foo_articles/how-to-reduce-the-intake-of-junk-food-in-children/
foo_articles is my post type and its a change able
Now my question is how can i set links that when a user set permalinks Custom Structure and set value like %category%/%postname% my link also change like above default post single page.
http://localhost/foo_articles/article cat slug/how-to-reduce-the-intake-of-junk-food-in-children/
Here is custom post type code:
add_action('init', 'foo_articles');
function foo_articles() {
$foo_slug = 'foo_articles';
$foo_slug = get_option('foo_plugin_slug');
$labels = array(
'name' => __('Foo', 'fff'),
'singular_name' => __('Foo', 'fff'),
'all_items' => __('Articles', 'fff'),
'add_new' => __('New Article', 'fff'),
'add_new_item' => __('Add New Article', 'fff'),
'edit_item' => __('Edit Article', 'fff'),
'new_item' => __('New Article', 'fff'),
'view_item' => __('View Articles', 'fff'),
'search_items' => __('Search Articles', 'fff'),
'not_found' => __('Nothing found', 'fff'),
'not_found_in_trash' => __('Nothing found in Trash', 'fff'),
'parent_item_colon' => ''
);
$foo_rewrite = array(
'slug' => FOO_PLUGIN_SLUG, // i define this in plugin index file
'with_front' => true,
'pages' => false,
'feeds' => true,
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'menu_icon' => plugin directory.'images/icon-foo.png',
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 3,
'supports' => array('title','editor','thumbnail','comments','tags'),
'rewrite' => $foo_rewrite,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => true
);
register_post_type( 'foo_articles' , $args );
flush_rewrite_rules();
}
add_action( 'init', 'foo_taxonomies', 0 );
// Article taxonamy
function foo_taxonomies() {
// Add new taxonomy, make it hierarchical (like categories)
$labels = array(
'name' => __( 'Article Category', 'fff'),
'singular_name' => __( 'Article Category', 'fff' ),
'search_items' => __( 'Search Article Category', 'fff' ),
'all_items' => __( 'All Article Categories', 'fff' ),
'parent_item' => __( 'Parent Article Category', 'fff' ),
'parent_item_colon' => __( 'Parent Article Category:', 'fff' ),
'edit_item' => __( 'Edit Article Category', 'fff' ),
'update_item' => __( 'Update Article Category', 'fff' ),
'add_new_item' => __( 'Add New Article Category', 'fff' ),
'new_item_name' => __( 'New Article Category Name', 'fff' ),
'menu_name' => __( 'Categories', 'fff' )
);
register_taxonomy( 'foo_categories', array( 'foo_articles' ), array(
'hierarchical' => true,
"labels" => $labels,
"singular_label" => __( 'Foo Category', 'foo'),
'show_ui' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'foo_category', 'with_front' => true )
));
flush_rewrite_rules();
}
Note: i change my post type slug by plugin settings and its option_name is foo_plugin_slug (its a client idea)
So please tell me how can i do this. Is there any hook or filter or htaccess code
You can use WP Walker concept. Please check this
WP Walker
Eg:
Use ACF plugin to get custom field.
List pages code :-
$args = array(
'child_of' => $post->ID,
'date_format' => get_option('date_format'),
'post_type' => 'page',
'title_li' => __(''),
'walker' => new my_page_walker
);
wp_list_pages( $args );
Extend Walker_page in function.php
In function.php
class my_page_walker extends Walker_Page {
public function start_el( &$output, $page, $depth = 0, $args = array(), $current_page = 0 ) {
if ( $depth ) {
$indent = str_repeat( "\t", $depth );
} else {
$indent = '';
}
$css_class = array( 'page_item', 'page-item-' . $page->ID );
if ( isset( $args['pages_with_children'][ $page->ID ] ) ) {
$css_class[] = 'page_item_has_children';
}
if ( ! empty( $current_page ) ) {
$_current_page = get_post( $current_page );
if ( $_current_page && in_array( $page->ID, $_current_page->ancestors ) ) {
$css_class[] = 'current_page_ancestor';
}
if ( $page->ID == $current_page ) {
$css_class[] = 'current_page_item';
} elseif ( $_current_page && $page->ID == $_current_page->post_parent ) {
$css_class[] = 'current_page_parent';
}
} elseif ( $page->ID == get_option('page_for_posts') ) {
$css_class[] = 'current_page_parent';
}
$css_classes = implode( ' ', apply_filters( 'page_css_class', $css_class, $page, $depth, $args, $current_page ) );
if ( '' === $page->post_title ) {
$page->post_title = sprintf( __( '#%d (no title)' ), $page->ID );
}
$args['link_before'] = empty( $args['link_before'] ) ? '' : $args['link_before'];
$args['link_after'] = empty( $args['link_after'] ) ? '' : $args['link_after'];
$page_permalink = get_permalink( $page->ID );
$user_defined_link = get_field('my-custom-field',$page->ID)['url'];
if (!is_null($user_defined_link)) {
$page_permalink = $user_defined_link;
}
$output .= $indent . sprintf(
'<li class="%s">%s%s%s',
$css_classes,
$page_permalink,
$args['link_before'],
apply_filters( 'the_title', $page->post_title, $page->ID ),
$args['link_after']
);
if ( ! empty( $args['show_date'] ) ) {
if ( 'modified' == $args['show_date'] ) {
$time = $page->post_modified;
} else {
$time = $page->post_date;
}
$date_format = empty( $args['date_format'] ) ? '' : $args['date_format'];
$output .= " " . mysql2date( $date_format, $time );
}
}
}
The final link will be the value from the custom field.

put custom field without using custom fields

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 ) );
}

Categories