Overriding a function in a class from the Wordpress plugin Elementor Pro about Product Upsells - wordpress

I would like to find a way to override the following file in the plugin Elementor Pro for wordpress to add an "else" in "protected function render()". I want to be able to display a message when there is no upsell available in my carrousel from element pro.
<?php
namespace ElementorPro\Modules\Woocommerce\Widgets;
use Elementor\Controls_Manager;
use Elementor\Core\Kits\Documents\Tabs\Global_Colors;
use Elementor\Core\Kits\Documents\Tabs\Global_Typography;
use Elementor\Group_Control_Typography;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class Product_Upsell extends Products_Base {
public function get_name() {
return 'woocommerce-product-upsell';
}
public function get_title() {
return esc_html__( 'Upsells', 'elementor-pro' );
}
public function get_icon() {
return 'eicon-product-upsell';
}
public function get_keywords() {
return [ 'woocommerce', 'shop', 'store', 'upsell', 'product' ];
}
protected function register_controls() {
$this->start_controls_section(
'section_upsell_content',
[
'label' => esc_html__( 'Upsells', 'elementor-pro' ),
]
);
$this->add_columns_responsive_control();
$this->add_control(
'orderby',
[
'label' => esc_html__( 'Order By', 'elementor-pro' ),
'type' => Controls_Manager::SELECT,
'default' => 'date',
'options' => [
'date' => esc_html__( 'Date', 'elementor-pro' ),
'title' => esc_html__( 'Title', 'elementor-pro' ),
'price' => esc_html__( 'Price', 'elementor-pro' ),
'popularity' => esc_html__( 'Popularity', 'elementor-pro' ),
'rating' => esc_html__( 'Rating', 'elementor-pro' ),
'rand' => esc_html__( 'Random', 'elementor-pro' ),
'menu_order' => esc_html__( 'Menu Order', 'elementor-pro' ),
],
]
);
$this->add_control(
'order',
[
'label' => esc_html__( 'Order', 'elementor-pro' ),
'type' => Controls_Manager::SELECT,
'default' => 'desc',
'options' => [
'asc' => esc_html__( 'ASC', 'elementor-pro' ),
'desc' => esc_html__( 'DESC', 'elementor-pro' ),
],
]
);
$this->end_controls_section();
parent::register_controls();
$this->start_injection( [
'at' => 'before',
'of' => 'section_design_box',
] );
$this->start_controls_section(
'section_heading_style',
[
'label' => esc_html__( 'Heading', 'elementor-pro' ),
'tab' => Controls_Manager::TAB_STYLE,
]
);
$this->add_control(
'show_heading',
[
'label' => esc_html__( 'Heading', 'elementor-pro' ),
'type' => Controls_Manager::SWITCHER,
'label_off' => esc_html__( 'Hide', 'elementor-pro' ),
'label_on' => esc_html__( 'Show', 'elementor-pro' ),
'default' => 'yes',
'return_value' => 'yes',
'prefix_class' => 'show-heading-',
]
);
$this->add_control(
'heading_color',
[
'label' => esc_html__( 'Color', 'elementor-pro' ),
'type' => Controls_Manager::COLOR,
'global' => [
'default' => Global_Colors::COLOR_PRIMARY,
],
'selectors' => [
'{{WRAPPER}}.elementor-wc-products .products > h2' => 'color: {{VALUE}}',
],
'condition' => [
'show_heading!' => '',
],
]
);
$this->add_group_control(
Group_Control_Typography::get_type(),
[
'name' => 'heading_typography',
'global' => [
'default' => Global_Typography::TYPOGRAPHY_PRIMARY,
],
'selector' => '{{WRAPPER}}.elementor-wc-products .products > h2',
'condition' => [
'show_heading!' => '',
],
]
);
$this->add_responsive_control(
'heading_text_align',
[
'label' => esc_html__( 'Text Align', 'elementor-pro' ),
'type' => Controls_Manager::CHOOSE,
'options' => [
'left' => [
'title' => esc_html__( 'Left', 'elementor-pro' ),
'icon' => 'eicon-text-align-left',
],
'center' => [
'title' => esc_html__( 'Center', 'elementor-pro' ),
'icon' => 'eicon-text-align-center',
],
'right' => [
'title' => esc_html__( 'Right', 'elementor-pro' ),
'icon' => 'eicon-text-align-right',
],
],
'selectors' => [
'{{WRAPPER}}.elementor-wc-products .products > h2' => 'text-align: {{VALUE}}',
],
'condition' => [
'show_heading!' => '',
],
]
);
$this->add_responsive_control(
'heading_spacing',
[
'label' => esc_html__( 'Spacing', 'elementor-pro' ),
'type' => Controls_Manager::SLIDER,
'size_units' => [ 'px', 'em' ],
'selectors' => [
'{{WRAPPER}}.elementor-wc-products .products > h2' => 'margin-bottom: {{SIZE}}{{UNIT}}',
],
'condition' => [
'show_heading!' => '',
],
]
);
$this->end_controls_section();
$this->end_injection();
}
protected function render() {
$settings = $this->get_settings_for_display();
// Add a wrapper class to the Add to Cart & View Items elements if the automically_align_buttons switch has been selected.
if ( 'yes' === $settings['automatically_align_buttons'] ) {
add_filter( 'woocommerce_loop_add_to_cart_link', [ $this, 'add_to_cart_wrapper' ], 10, 1 );
}
$limit = '-1';
$columns = 4;
$orderby = 'rand';
$order = 'desc';
if ( ! empty( $settings['columns'] ) ) {
$columns = $settings['columns'];
}
if ( ! empty( $settings['orderby'] ) ) {
$orderby = $settings['orderby'];
}
if ( ! empty( $settings['order'] ) ) {
$order = $settings['order'];
}
ob_start();
woocommerce_upsell_display(
sanitize_text_field( $limit ),
sanitize_text_field( $columns ),
sanitize_text_field( $orderby ),
sanitize_text_field( $order )
);
$upsells_html = ob_get_clean();
if ( $upsells_html ) {
$upsells_html = str_replace( '<ul class="products', '<ul class="products elementor-grid', $upsells_html );
// PHPCS - Doesn't need to be escaped since it's a WooCommerce template, and 3rd party plugins might hook into it.
echo $upsells_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
///////// The code I want to add ///////
else {
echo "no product available";
}
///////// The code I want to add ///////
if ( 'yes' === $settings['automatically_align_buttons'] ) {
remove_filter( 'woocommerce_loop_add_to_cart_link', [ $this, 'add_to_cart_wrapper' ] );
}
}
public function render_plain_content() {}
public function get_group_name() {
return 'woocommerce';
}
}
I tried many things but with no success. For example, put the same file in child theme with same path or calling it with the namespace. I can't use the filters and I have no idea how to do it properly. Right now it is working but if I update the plugin I loose the modification.

Related

Elementor access settings inside _register_controls function

I am using Elementor. In one section user can create categories with repeater field. In other section I would like to list these categories in Select2 control. How could I access category_data in _register_controls function? I know I can access it in render function.
protected function _register_controls() {
$this->start_controls_section(
'content_section',
[
'label' => __( 'Content', 'plugin-name' ),
'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
]
);
$repeater->add_control(
'category_title', [
'label' => esc_html__( 'Title', 'plugin-name'),
'type' => \Elementor\Controls_Manager::TEXT,
'label_block' => false,
]
);
$repeater->add_control(
'category_slug', [
'label' => esc_html__( 'Slug', 'plugin-name'),
'type' => \Elementor\Controls_Manager::TEXT,
'label_block' => false,
]
);
$this->add_control(
'category_data',
[
'label' => esc_html__( 'Category', 'plugin-name'),
'type' => \Elementor\Controls_Manager::REPEATER,
'fields' => $repeater->get_controls(),
'prevent_empty' => false,
'title_field' => '{{{ category_title }}}',
]
);
$this->end_controls_section();
$this->start_controls_section(
'category_section',
[
'label' => __( 'Category', 'plugin-name' ),
'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
]
);
//how could I access category_data here?
$settings = $this->get_settings_for_display();
$category_data = $settings['category_data'];
$cd_arr = [];
foreach ($category_data as $cd) {
$cd_arr[] = $cd['category_slug'];
}
if(count($cd_arr) > 0){
$this->add_control(
'media_category',
[
'label' => esc_html__( 'Categories', 'plugin-name'),
'type' => \Elementor\Controls_Manager::SELECT2,
'multiple' => true,
'options' => $cd_arr,
]
);
}
$this->end_controls_section();
}

WORDPRESS : Remove from the urls the prefix /custom-post-name/ in all my articles AND THEIR TRANSLATIONS made with Polylang

My theme was tailor-made by a developper.
All my (single-post) articles are custom posts.
By default the url of a custom post is : https://www.example.com/custom-post-name/slug
For very good reasons this prefix /custom-post-name/ had to be removed.
The developper of my theme achieved that by editing some code in the file declaring the custom post which is this one : wp-content/themes/mytheme/inc/custom-post-types.php
The custom-post-name as registered in this file is "article"
register_post_type( "article", $args );
I believe the part of code removing the prefix /custom-post-name/ from the urls is :
function gp_remove_cpt_slug( $post_link, $post, $leavename ) {
if ( 'article' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'gp_remove_cpt_slug', 10, 3 );
It has worked fine until now that I want to translate my website.
The translated articles get this url :
https://www.example.com/en/slug
The result is a 404 error
If I add (by hand) in the url the prefix custom-post-name that way :
https://www.example.com/en/custom-post-name/slug
Then it works.
What I need is to get completely rid of this prefix for my custom-post-type registered with the name "article". In the default language AND IN THE TRANSLATED versions made with the plugin Polylang
The complete code of my file wp-content/themes/mytheme/inc/custom-post-types.php is this :
<?php
function cptui_register_my_cpts_module() {
$labels = array(
"name" => __( "Modules", "" ),
"singular_name" => __( "Module", "" ),
);
$args = array(
"label" => __( "Modules", "" ),
"labels" => $labels,
"description" => "",
"public" => false,
"publicly_queryable" => false,
"show_ui" => true,
"show_in_rest" => false,
"rest_base" => "",
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => true,
"capability_type" => "page",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "module", "with_front" => true ),
"query_var" => true,
"menu_icon" => "dashicons-schedule",
"supports" => array( "title", "page-attributes" ),
);
register_post_type( "module", $args );
$labels = array(
"name" => __( "Articles", "" ),
"singular_name" => __( "Article", "" ),
);
$args = array(
"label" => __( "Articles", "" ),
"labels" => $labels,
"description" => "",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"show_in_rest" => false,
"rest_base" => "",
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "page",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "article", "with_front" => true ),
"query_var" => true,
//"menu_icon" => "dashicons-schedule",
"menu_position" => 5,
"supports" => array( "title", "page-attributes", "comments", "editor" ),
"taxonomies" => array( "categorie" ),
);
register_post_type( "article", $args );
}
add_action( 'init', 'cptui_register_my_cpts_module' );
function cptui_register_my_taxes_categorie() {
/**
* Taxonomy: Catégories.
*/
$labels = array(
"name" => __( "Catégories", "" ),
"singular_name" => __( "Catégorie", "" ),
);
$args = array(
"label" => __( "Catégories", "" ),
"labels" => $labels,
"public" => true,
"hierarchical" => true,
"label" => "Catégories",
"show_ui" => true,
"show_in_menu" => true,
"show_in_nav_menus" => true,
"query_var" => true,
"rewrite" => array( 'slug' => 'categorie', 'with_front' => true, ),
"show_admin_column" => true,
"show_in_rest" => false,
"rest_base" => "",
"show_in_quick_edit" => true,
);
register_taxonomy( "categorie", array( "article" ), $args );
}
add_action( 'init', 'cptui_register_my_taxes_categorie' );
function gp_remove_cpt_slug( $post_link, $post, $leavename ) {
if ( 'article' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'gp_remove_cpt_slug', 10, 3 );
function gp_add_cpt_post_names_to_main_query( $query ) {
// Bail if this is not the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Bail if this query doesn't match our very specific rewrite rule.
if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
return;
}
// Bail if we're not querying based on the post name.
if ( empty( $query->query['name'] ) ) {
return;
}
// Add CPT to the list of post types WP will include when it queries based on the post name.
$query->set( 'post_type', array( 'post', 'page', 'article' ) );
}
add_action( 'pre_get_posts', 'gp_add_cpt_post_names_to_main_query' );
add_filter('request', 'rudr_change_term_request', 1, 1 );
function rudr_change_term_request($query){
$tax_name = 'categorie'; // specify you taxonomy name here, it can be also 'category' or 'post_tag'
// Request for child terms differs, we should make an additional check
if( $query['attachment'] ) :
$include_children = true;
$name = $query['attachment'];
else:
$include_children = false;
$name = $query['name'];
endif;
$term = get_term_by('slug', $name, $tax_name); // get the current term to make sure it exists
if (isset($name) && $term && !is_wp_error($term)): // check it here
if( $include_children ) {
unset($query['attachment']);
$parent = $term->parent;
while( $parent ) {
$parent_term = get_term( $parent, $tax_name);
$name = $parent_term->slug . '/' . $name;
$parent = $parent_term->parent;
}
} else {
unset($query['name']);
}
switch( $tax_name ):
/* case 'category':{
$query['category_name'] = $name; // for categories
break;
}
case 'post_tag':{
$query['tag'] = $name; // for post tags
break;
}*/
default:{
$query[$tax_name] = $name; // for another taxonomies
break;
}
endswitch;
endif;
return $query;
}
add_filter( 'term_link', 'rudr_term_permalink', 10, 3 );
function rudr_term_permalink( $url, $term, $taxonomy ){
$taxonomy_name = 'categorie'; // your taxonomy name here
$taxonomy_slug = 'categorie'; // the taxonomy slug can be different with the taxonomy name (like 'post_tag' and 'tag' )
// exit the function if taxonomy slug is not in URL
if ( strpos($url, $taxonomy_slug) === FALSE || $taxonomy != $taxonomy_name ) return $url;
$url = str_replace('/' . $taxonomy_slug, '', $url);
return $url;
}
?>
Thanks a lot for reading and any help,
François

ZF3 Multiple Controllers in same Module

I am learning ZF3, i am trying to add InfoController to the Album module. would my URL be ....../album/info? I am getting 404 error occurred. I have seen John Deck's post and implemented exactly the same, but still not working
This is my module.config.php
<?php
namespace Album;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return array(
'controllers' => [
'factories' => [
Controller\InfoController::class => function($container) {
return new Controller\InfoController(
$container->get(\Album\Model\InfoTable::class)
);
},
Controller\AlbumController::class => function($container) {
return new Controller\AlbumController(
$container->get(\Album\Model\AlbumTable::class)
);
},
],
'aliases' => [
'index' => AlbumController::class,
'info' => InfoController::class,
]
],
'router' => array(
'routes' => array(
'album' => array(
'type' => Segment::class,
'options' => array(
'route' => '/album[/:action[/:id]]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\AlbumController',//Controller::class,
'action' => 'index',
),
),
),
'info' => array(
'type' => Segment::class,
'options' => array(
//'route' => 'Album/Controller/Info[/:action[/:id]]',
'route' => '/InfoController[/:action[/:id]]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Album\Controller\Info',//::class
'action' => 'index',
),
),
),
),
),
'view_manager' => [
'display_not_found_reason' => false,
'display_exceptions' => false,
'doctype' => 'HTML5',
'template_map' => [
'layout/album' => __DIR__ . '/../view/layout/album_layout.phtml',
'album/album/index' => __DIR__ . '/../view/album/album/index.phtml',
'layout/album' => __DIR__ . '/../view/layout/info_layout.phtml',
'info/info/index' => __DIR__ . '/../view/info/info/index.phtml',
],
'template_path_stack' => [
'Album' => __DIR__ . '/../view',
'Info' => __DIR__ . '/../view',
],
],
);
Here's my Module.php
<?php
namespace Album;
use Album\Model\InfoTable;
use Album\Model\Info;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return array(
'factories' => array(
Model\AlbumTable::class => function($container) {
$tableGateway = $container->get(Model\AlbumTableGateway::class);
return new Model\AlbumTable($tableGateway);
},
Model\AlbumTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
Model\InfoTable::class => function($container) {
$tableGateway = $container->get(Model\InfoTableGateway::class);
return new Model\InfoTable($tableGateway);
},
Model\InfoTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Info());
return new TableGateway('info', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
public function getControllerConfig()
{
return array(
'factories' => array(
Controller\AlbumController::class => function($container) {
return new Controller\AlbumController(
$container->get(Model\AlbumTable::class)
);
},
Controller\InfoController::class => function($container) {
return new Controller\InfoController(
$container->get(Model\InfoTable::class)
);
},
),
);
}
}

WordPress Plugin development: Category filter in media library makes the page to reload

I am building a plugin where I have a dropdown category filter on media library.
The filter works fine on list view but on grid view mode when I select a category, rather than media files getting filtered the page refreshes and nothing is filtering.
I am not using any custom taxonomy, so I have register the taxonomy (in my case it is category to attachment post type)
function register_taxonomy_for_post_type() {
//$this->taxonomy = apply_filters( 'cool_media_taxonomy', $this->taxonomy );
if( taxonomy_exists( $this->taxonomy ) ) {
register_taxonomy_for_object_type( $this->taxonomy, $this->post_type );
} else {
$args = array(
'hierarchical' => true,
'show_admin_column' => true,
'update_count_callback' => array( $this, 'update_count' ),
);
register_taxonomy( $this->taxonomy, array( $this->post_type ), $args );
}
}
add_action( 'init', array( $this, 'register_taxonomy_for_post_type' ), 0 );
Localization:
function enqueue_media_action() {
require_once plugin_dir_path( __FILE__ ) . 'classes/class-walker-category-mediagrid-filter.php';
global $pagenow;
if( wp_script_is( 'media-editor' ) && 'upload.php' === $pagenow ) {
if( $this->taxonomy !== 'category' ) {
$options = array(
'taxonomy' => $this->taxonomy,
'hierarchical' => true,
'hide_empty' => false,
'show_count' => true,
'orderby' => 'name',
'order' => 'ASC',
'value' => 'id',
'echo' => false,
'walker' => new WalkerCategoryMediaGridFilter(),
);
} else {
$options = array(
'taxonomy' => $this->taxonomy,
'hierarchical' => true,
'hide_empty' => false,
'show_count' => true,
'orderby' => 'name',
'order' => 'ASC',
'value' => 'id',
'echo' => false,
'walker' => new WalkerCategoryMediaGridFilter(),
);
}
$attachment_terms = wp_dropdown_categories( $options );
$attachment_terms = preg_replace( array( "/<select([^>]*)>/", "/<\/select>/" ), "", $attachment_terms );
echo '<script type="text/javascript">';
echo '/* <![CDATA[ */';
echo 'var coolmediafilter_taxonomies = {"' . $this->taxonomy . '":{"list_title":"' . html_entity_decode( __( 'All categories', $this->text_domain ), ENT_QUOTES, 'UTF-8' ) . '","term_list":[' . substr( $attachment_terms, 2 ) . ']}};';
echo '/* ]]> */';
echo '</script>';
wp_enqueue_script('coolmediafilter-media-views', plugins_url( 'js/cmf-media-views.js', __FILE__ ), array( 'media-views' ), '1.0.0', true );
$cats = $this->get_accessible_categories();
$filtered_cats = array(
'hide_empty' => false,
'include' => $cats,
'orderby' => 'name',
'order' => 'ASC',
);
wp_localize_script( 'coolmediafilter-media-views', 'MediaLibraryCategoryFilterOptions',
array(
'terms' => get_terms(
$this->taxonomy,
$filtered_cats
),
)
);
}
wp_enqueue_style( 'coolmediafilter', plugins_url( 'css/coolmediafilter.css', __FILE__ ), array(), '1.0.0' );
}
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_media_action' ) );
The script:
(function(){
/**
* Create a new MediaLibraryTaxonomyFilter we later will instantiate
*/
var MediaLibraryCategoryFilter = wp.media.view.AttachmentFilters.extend({
id: 'media-view-category-filter',
createFilters: function() {
var filters = {};
// Formats the 'terms' we've included via wp_localize_script()
_.each( MediaLibraryCategoryFilterOptions.terms || {}, function( value, index ) {
filters[ value.term_id ] = {
text: value.name,
props: {
// The WP_Query var for the taxonomy
category: value.term_id,
}
};
});
filters.all = {
// Default label
text: 'All categories',
props: {
// The WP_Query var for the taxonomy
category: ''
},
priority: 10
};
this.filters = filters;
}
});
/**
* Extend and override wp.media.view.AttachmentsBrowser to include our new filter
*/
var AttachmentsBrowser = wp.media.view.AttachmentsBrowser;
wp.media.view.AttachmentsBrowser = wp.media.view.AttachmentsBrowser.extend({
createToolbar: function() {
// Make sure to load the original toolbar
AttachmentsBrowser.prototype.createToolbar.call( this );
this.toolbar.set( 'MediaLibraryCategoryFilter', new MediaLibraryCategoryFilter({
controller: this.controller,
model: this.collection.props,
priority: -75
}).render() );
}
});
})()
what I am doing wrong? Any suggestion will be very helpful.
UPDATE: Screenshot of console from FireFox

Wp custom plugins meta filed box are not visible

I have created a plugins about to save Authorz data using wordpress custom fields and meta box. The Plugins has no errors and running but the Meta boxes are not showing.
The plugins is running and i have attached the screenshot.
http://i63.tinypic.com/2czebyh.png
Below is my plugin code
<?php
/*Plugin Name: CNSLounge
Description: This plugin registers the 'Authors CNSLounge' post type.
Version: 1.0
Author: Anita Mandal
Author URI: http://cosmoread.com/
License: GPLv2
*/
// Register Custom Post Type
function CNSLounge() {
register_post_type('CNSLounge', array(
'labels' => array(
'name' => 'Authorz',
'singular_name' => 'Authorz',
'add_new' => 'Add New',
'add_new_item' => 'Add New Authorz',
'edit' => 'Edit',
'edit_item' => 'Edit Authorz',
'new_item' => 'New Authorz',
'view' => 'View',
'view_item' => 'View Authorz',
'search_items' => 'Search Authorz',
'not_found' => 'No Authorz found',
'not_found_in_trash' => 'No Authorz found in Trash',
'parent' => 'Parent Authorz'
),
'public' => true,
'menu_position' => 15,
'supports' => array(
'title',
'editor',
'comments',
'thumbnail'
),
'taxonomies' => array(
''
),
'menu_icon' => plugins_url('images/image.png', __FILE__),
'has_archive' => true
));
register_post_type( 'post_type', $args );
}
add_action( 'init', 'CNSLounge', 0 );
class Rational_Meta_Box {
private $screens = array(
'post',
);
private $fields = array(
array(
'id' => 'authorz-name',
'label' => 'Authorz Name',
'type' => 'text',
),
array(
'id' => 'author-photo',
'label' => 'Author Photo',
'type' => 'media',
),
array(
'id' => 'active-since',
'label' => 'Active Since',
'type' => 'date',
),
array(
'id' => 'languages-expression',
'label' => 'Languages Expression',
'type' => 'text',
),
array(
'id' => 'now-based-at',
'label' => 'Now Based at',
'type' => 'text',
),
array(
'id' => 'location-of-author',
'label' => 'Location of Author',
'type' => 'text',
),
array(
'id' => 'mostly-writes',
'label' => 'Mostly Writes',
'type' => 'text',
),
array(
'id' => 'about-author',
'label' => 'About Author',
'type' => 'textarea',
),
array(
'id' => 'magazines',
'label' => 'Magazines',
'type' => 'media',
),
array(
'id' => 'publication',
'label' => 'Publication',
'type' => 'media',
),
array(
'id' => 'gallery',
'label' => 'Gallery',
'type' => 'media',
),
array(
'id' => 'author-s-website',
'label' => 'Author\'s Website',
'type' => 'url',
),
array(
'id' => 'author-s-email',
'label' => 'Author\'s Email',
'type' => 'email',
),
array(
'id' => 'author-s-phone',
'label' => 'Author\'s Phone',
'type' => 'number',
),
);
/**
* 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(
'cnslounge',
__( 'CNSLounge', 'rational-metabox' ),
array( $this, 'add_meta_box_callback' ),
$screen,
'advanced',
'default'
);
}
}
/**
* Generates the HTML for the meta box
*
* #param object $post WordPress post object
*/
public function add_meta_box_callback( $post ) {
wp_nonce_field( 'cnslounge_data', 'cnslounge_nonce' );
echo 'CNSLounge Author Meta Information';
$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, 'advanced_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;
case 'textarea':
$input = sprintf(
'<textarea class="large-text" id="%s" name="%s" rows="5">%s</textarea>',
$field['id'],
$field['id'],
$db_value
);
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['cnslounge_nonce'] ) )
return $post_id;
$nonce = $_POST['cnslounge_nonce'];
if ( !wp_verify_nonce( $nonce, 'cnslounge_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, 'cnslounge_' . $field['id'], $_POST[ $field['id'] ] );
} else if ( $field['type'] === 'checkbox' ) {
update_post_meta( $post_id, 'cnslounge_' . $field['id'], '0' );
}
}
}
}
new Rational_Meta_Box;
?>
private $screens = array(
'post',
);
So, you are adding the metaboxes to post, not to your custom post type.
Use your custom post type slug here. just like
private $screens = array(
'CNSLounge',
);

Resources