I have products from some API and want to insert these products. I was able to insert products and use already existing attributes ( or added by UI ).
Adding new term (My Color) to the existing attribute (Color) :
// Add term to the attribute
wp_set_object_terms( $post_id, "My Color", 'pa_color' , true );
Use the added attribute with current product :
// Data for the term to be used
$theData = array(
'pa_color'=>
array(
'name'=>'pa_color',
'value'='My Color',
'is_visible' => '1',
'is_variation' => '1',
'is_taxonomy' => '1'
)
);
// Add this attribute to this product
update_post_meta( $post_id,'_product_attributes',$theData);
How can I add new attribute and use it with the current product, for ex :
RAM : 4GB
I have tried this :
register_taxonomy(
'pa_ram',
'product',
array(
'label' => __( 'RAM' ),
'rewrite' => array( 'slug' => 'size' ),
'hierarchical' => true,
)
);
}
Here is the URL of the attributes I can see/add in UI :
wp-admin/edit.php?post_type=product&page=product_attributes
This did the job for me :
// Insert new attribute
function process_add_attribute($attribute) {
global $wpdb;
if (empty($attribute['attribute_type'])) {
$attribute['attribute_type'] = 'select';
}
if (empty($attribute['attribute_orderby'])) {
$attribute['attribute_orderby'] = 'name';
}
if (empty($attribute['attribute_public'])) {
$attribute['attribute_public'] = 1;
}
if (empty($attribute['attribute_name']) || empty($attribute['attribute_label'])) {
return new WP_Error('error', __('Please, provide an attribute name and slug.', 'woocommerce'));
}
elseif(($valid_attribute_name = valid_attribute_name($attribute['attribute_name'])) && is_wp_error($valid_attribute_name)) {
return $valid_attribute_name;
}
$wpdb->insert($wpdb->prefix.'woocommerce_attribute_taxonomies', $attribute);
do_action('woocommerce_attribute_added', $wpdb->insert_id, $attribute);
flush_rewrite_rules();
delete_transient('wc_attribute_taxonomies');
return true;
}
function valid_attribute_name( $attribute_name ) {
if ( strlen( $attribute_name ) >= 28 ) {
return new WP_Error( 'error', sprintf( __( 'Slug "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), sanitize_title( $attribute_name ) ) );
} elseif ( wc_check_if_attribute_name_is_reserved( $attribute_name ) ) {
return new WP_Error( 'error', sprintf( __( 'Slug "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), sanitize_title( $attribute_name ) ) );
}
return true;
}
Call it like :
// Add new attribute
$status = process_add_attribute(array(
'attribute_name' => 'myattribute',
'attribute_label' => 'My Attribute'
));
// Added successfully
if (!is_wp_error($status)) {
// Continue
}
Related
This is an extension for elementor pro forms that sends the form data to an API.
This first API will return a success or failure message.
If successful, the response will also contain an ID number.
That ID number should then be used in a second API request where the number is appended to the URL. This second API will return a login URL.
The plugin should then redirect the user to the returned URL.
Currently I am receiving a response from the first API. the response I've received is as follows:
{"code":201,"data":{"id":133714},"message":"Success"}
The second API Response I get is the following:
{"code": 200,"request_method":"GET","autologin":"https://www.exampleurl.com/login" }
But it is not redirecting the user. Can you help me discover why?
`
<?php
/*
Plugin Name: Elementor Custom form
Plugin URI:
Description:
Version:
Author:
Author URI:
License:
License URI:
*/
/*
This plugin adds a custom form action to Elementor Pro forms.
The new action sends an API Request to a custom endpoint.
After receiving a valid response, the form will send another API Request to a different endpoint.
The response from the second API Request is used to redirect the user to a different page.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class Bpd_Custom_Form_Action extends \ElementorPro\Modules\Forms\Classes\Action_Base {
public function get_name() {
return 'custom_form_action';
}
public function get_label() {
return __( 'Custom Form Action', 'elementor-pro' );
}
public function register_settings_section( $widget ) {
$widget->start_controls_section(
'section_custom_form_action',
[
'label' => $this->get_label(),
'condition' => [
'submit_actions' => $this->get_name(),
],
]
);
//////////////////////////////////////////////
//
// FIRST API - SETTINGS & AUTHORIZATION
//
//////////////////////////////////////////////
$widget->add_control(
'custom_form_action_api_url',
[
'label' => __( 'URL', 'elementor-pro' ),
'type' => \Elementor\Controls_Manager::TEXT,
'placeholder' => 'https://example.com/api/',
'description' => __( 'Enter the URL of the API endpoint you want to send the form data to.', 'elementor-pro' ),
'label_block' => true,
'separator' => 'before',
]
);
$widget->add_control(
'custom_form_action_application_token',
[
'label' => __( 'Application Token', 'elementor-pro' ),
'type' => \Elementor\Controls_Manager::TEXT,
'placeholder' => 'https://example.com/api/',
'label_block' => true,
'description' => __( 'Enter the application token for your API request.', 'elementor-pro' ),
'separator' => 'before',
]
);
//////////////////////////////////////////////
//
// FIRST API - Body & Response Options
//
//////////////////////////////////////////////
$widget->add_control(
'custom_form_action_api_body',
[
'label' => __( 'Body', 'elementor-pro' ),
'type' => \Elementor\Controls_Manager::TEXTAREA,
'placeholder' => '{ "name": "{{{ name }}}", "email": "{{{ email }}}" "ip": "{{{ USERIP }}}" }',
'description' => __( 'Enter the body of the API request. You can use the form fields as placeholders. For example: { "name": "{{{ name }}}", "email": "{{{ email }}}" }', 'elementor-pro' ),
'label_block' => true,
'separator' => 'before',
]
);
//////////////////////////////////////////////
//
// Second API - SETTINGS & AUTHORIZATION
//
//////////////////////////////////////////////
$widget->add_control(
'custom_form_action_second_api_url',
[
'label' => __( 'Second API URL', 'elementor-pro' ),
'type' => \Elementor\Controls_Manager::TEXT,
'placeholder' => 'https://example.com/thank-you/',
'description' => __( 'Enter the URL of the page you want to redirect the user to after the form is submitted.', 'elementor-pro' ),
'label_block' => true,
'separator' => 'before',
]
);
$widget->add_control(
'custom_form_action_second_application_token',
[
'label' => __( 'Second Application Token', 'elementor-pro' ),
'type' => \Elementor\Controls_Manager::TEXT,
'placeholder' => 'https://example.com/api/',
'label_block' => true,
'description' => __( 'Enter the application token for your API request.', 'elementor-pro' ),
'separator' => 'before',
]
);
$widget->end_controls_section();
}
public function register_form_action( $widget ) {
$widget->add_form_action(
'custom_form_action',
[
'label' => __( 'Custom Form Action', 'elementor-pro' ),
'event' => \ElementorPro\Modules\Forms\Classes\Form_Record::get_form_settings( 'custom_form_action_event' ),
'callback' => [ $this, 'custom_form_action' ],
]
);
}
public function run( $record, $ajax_handler ) {
$debugLog = '';
$settings = $record->get( 'form_settings' );
// create the first api request
$first_api_url = $settings['custom_form_action_api_url'];
$first_api_body = $settings['custom_form_action_api_body'];
// set up the first header request
$first_api_header_authorization = 'Bearer ' . $settings['custom_form_action_application_token'];
// get the form fields
$fields = $record->get( 'fields' );
// replace the placeholders with the form field values
$first_api_body = $this->replace_placeholders( $first_api_body, $fields );
//////////////////////////////////////////
//
// Make the first API request
//
//////////////////////////////////////////
//if the method is post
// send the post request
$first_api_response = wp_remote_post( $first_api_url, [
'method' => 'POST',
'headers' => array(
'Authorization' => 'Bearer ' . $settings['custom_form_action_application_token'],
'content-type' => 'application/json',
),
'body' => $first_api_body,
'timeout' => 20,
'redirection' => 5,
'httpversion' => '1.0',
//SET BLOCKING TO TRUE TO WAIT FOR A RESPONSE - 5 hours wasted for this.
'blocking' => true,
'data_format' => 'body',
] );
if ( ! is_wp_error( $first_api_response ) ) {
$response_data = json_decode( $first_api_response['body'], true );
if ( isset( $response_data['data']['id'] ) ) {
$new_lead_id = $response_data['data']['id'];
}
else{
$new_lead_id = '';
}
}
//////////////////////////////////////////
//
// Make the second API request
//
//////////////////////////////////////////
// create the second api request
$second_api_url = $settings['custom_form_action_second_api_url'];
// set up the second header request
$second_api_header_authorization = 'Bearer ' . $settings['custom_form_action_second_application_token'];
if (!empty($first_api_response_body)){
$new_lead_id = $first_api_response_body->data->id;
}
$new_api_url = $second_api_url . $new_lead_id;
$new_api_body = '{ "lead_id": ' . $new_lead_id . '}';
// send the second api request
$second_api_response = wp_remote_post( $new_api_url, [
'method' => 'POST',
'headers' => array(
'Authorization' => 'Bearer ' . $second_api_header_authorization,
'content-type' => 'application/json',
),
'body' => $new_api_body,
'timeout' => 20,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'data_format' => 'body',
] );
//Check for errors in the Second api response.
if ( ! is_wp_error( $second_api_response ) ) {
$response_data = json_decode( $second_api_response['body'], true );
if ( isset( $response_data['autologin'] ) ) {
$autologin = $response_data['autologin'];
}
else{
$autologin = 'https://google.com';
}
}
//redirect the user
if ( ! empty( $autologin ) ) {
wp_redirect( $autologin );
exit;
}
else{
wp_redirect( 'https://www.google.com' );
exit;
}
if ( is_wp_error( $first_api_response ) ) {
wp_remote_retrieve_response_code( $second_api_response );
if ( wp_remote_retrieve_response_code( $second_api_response ) == 201 ) {
//add success message
$ajax_handler->add_success_message( __( 'First API Response: ' . $second_api_response['body'], 'elementor-pro' ) );
}
elseif ( wp_remote_retrieve_response_code( $second_api_response ) == 202 ) {
//add error message
$ajax_handler->add_error_message( __( 'First API Response: ' . $second_api_response['body'], 'elementor-pro' ) );
}
}
if ( is_wp_error( $second_api_response ) ) {
$ajax_handler->add_error_message( __( '<br><br>Data ID From First Response: '. $first_api_response_body->data->id
. '<br>Second API Body: ' . json_encode($second_api_body)
. '<br> First API Response Selector: ' . $first_api_body_response_selector
. '<br>Second API Response: ' . $second_api_response['body']
. '<br>Redirect URL: ' . $redirect_response_url
. '<br><br>',
'elementor-pro'
)
);
return;
}
if ( ! empty( $redirect_response_url ) && filter_var( $redirect_response_url, FILTER_VALIDATE_URL ) ) {
$ajax_handler->add_response_data( 'redirect_url', $redirect_response_url );
}
}//end run function
public function on_export( $element ) {
unset( $element['custom_form_action_message_redirect_url'] );
return $element;
}
public function replace_placeholders( $string, $fields ) {
$ip_of_current_user = $this->bpd_get_user_ip();
foreach ( $fields as $id => $field ) {
$string = str_replace( '{{{ USERIP }}}', $ip_of_current_user, $string );
$string = str_replace( '{{{ ' . $id . ' }}}', $field['value'], $string );
}
return $string;
}
public function bpd_get_user_ip() {
/*
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
return $ip;
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
return $ip;
} else {
$ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}
*/
$ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}
}
`
I want to add a new attribute to an existing woocommerce product. I use this code
$pf = new WC_Product_Factory();
$product = $pf->get_product(76);
//Create the attribute object
$attribute = new WC_Product_Attribute();
$attribute->set_id( 0 );
//pa_color slug
$attribute->set_name( 'color' );
//Set terms slugs
$attribute->set_options( array(
'blue',
) );
$attribute->set_position( 0 );
//If enabled
$attribute->set_visible( 1 );
$product->set_attributes(array($attribute));
$id = $product->save();
this code working fine but I want to add attributes with terms, this code create custom product attribute.
I want to create attribute like this image
How can I create key-value attributes?
Try this code
function get_attribute_id_from_name($name)
{
global $wpdb;
$attribute_id = $wpdb->get_var("SELECT attribute_id
FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
WHERE attribute_name LIKE '$name'");
return $attribute_id;
}
function save_product_attribute_from_name($name, $label = '', $set = true)
{
if (!function_exists('get_attribute_id_from_name')){
return;
}
global $wpdb;
$label = $label == '' ? ucfirst($name) : $label;
$attribute_id = get_attribute_id_from_name($name);
$taxonomy = wc_attribute_taxonomy_name($name); // The taxonomy slug
if (empty($attribute_id)) {
$attribute_id = NULL;
}
else {
$set = false;
}
//register existing taxonomy
if (isset($attribute_id) && !taxonomy_exists($taxonomy)) {
register_attribute($name);
}
$args = array(
'attribute_id' => $attribute_id,
'attribute_name' => $name,
'attribute_label' => $label,
'attribute_type' => 'select',
'attribute_orderby' => 'menu_order',
'attribute_public' => 0,
);
if (empty($attribute_id)) {
$wpdb->insert("{$wpdb->prefix}woocommerce_attribute_taxonomies", $args);
set_transient('wc_attribute_taxonomies', false);
}
if ($set) {
$attributes = wc_get_attribute_taxonomies();
$args['attribute_id'] = get_attribute_id_from_name($name);
$attributes[] = (object)$args;
//print_r($attributes);
set_transient('wc_attribute_taxonomies', $attributes);
} else {
return;
}
}
function register_attribute($name)
{
$taxonomy = wc_attribute_taxonomy_name($name); // The taxonomy slug
$attr_label = ucfirst($name); // attribute label name
$attr_name = (wc_sanitize_taxonomy_name($name)); // attribute slug
register_taxonomy(
$taxonomy,
'product',
array(
'label' => __($attr_label),
'rewrite' => array('slug' => $attr_name),
'hierarchical' => true,
)
);
}
function add_product_attribute($product_id, $data)
{
$_pf = new WC_Product_Factory();
$product = $_pf->get_product($product_id);
$product_attributes = array();
foreach ($data['_attributes'] as $key => $terms) {
$taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
$attr_label = ucfirst($key); // attribute label name
$attr_name = (wc_sanitize_taxonomy_name($key)); // attribute slug
// NEW Attributes: Register and save them
if (!taxonomy_exists($taxonomy))
save_product_attribute_from_name($attr_name, $attr_label);
$product_attributes[$taxonomy] = array(
'name' => $taxonomy,
'value' => '',
'position' => '',
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 1
);
foreach ($terms as $value) {
$term_name = ucfirst($value);
$term_slug = sanitize_title($value);
// Check if the Term name exist and if not we create it.
if (!term_exists($value, $taxonomy))
wp_insert_term($term_name, $taxonomy, array('slug' => $term_slug)); // Create the term
// Set attribute values
wp_set_object_terms($product_id, $term_name, $taxonomy, true);
}
$product->set_attributes(array($attribute));
}
update_post_meta($product_id, '_product_attributes', $product_attributes);
}
Then call function
add_product_attribute(76, [
'attributes' => [
'Attribute 1' => ['Value 1', 'Value 2'],
'Attribute 2' => ['Value 4', 'Value 5'],
],
]
);
I am trying to update my repeater field from front end-with files. In case with one field file - it works. But when I'm trying to fill repeater with files it doesn't work.
// JS. Ajaxly sending files
var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
$('.js-new-msg-send').click(function (e) {
e.preventDefault();
var form = document.forms.namedItem("new_theme");
var formData = new FormData(form);
formData.append('user_id', '<?php echo $userID; ?>');
formData.append('action', 'msg_to_acf');
var xhr = new XMLHttpRequest();
xhr.open('POST', ajaxurl, true);
xhr.send(formData);
})
I found function to handle files uploading to acf field and modified it to handle multiple files from $_FILES variable:
// FOR MULTIPLE FILES
if ( !empty($_FILES[$f]['name']) && is_array($_FILES[$f]['name']) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$file_list = array();
foreach ($_FILES[$f]['name'] as $key => $value) {
$temp_file = array(
'name' => $_FILES[$f]['name'][$key],
'type' => $_FILES[$f]['type'][$key],
'tmp_name' => $_FILES[$f]['tmp_name'][$key],
'error' => $_FILES[$f]['error'][$key],
'size' => $_FILES[$f]['size'][$key]
);
wp_update_attachment_metadata( $pid, $temp_file );
$file = wp_handle_upload( $temp_file , array('test_form' => FALSE, 'action' => 'editpost') );
if ( isset( $file['error'] )) {
return new WP_Error( 'upload_error', $file['error'] );
}
$file_type = wp_check_filetype($temp_file['name'], array(
'jpg|jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
));
if ($file_type['type']) {
$name_parts = pathinfo( $file['file'] );
$name = $file['filename'];
$type = $file['type'];
$title = $t ? $t : $name;
$content = $c;
$attachment = array(
'post_title' => $title,
'post_type' => 'attachment',
'post_content' => $content,
'post_parent' => $pid,
'post_mime_type' => $type,
'guid' => $file['url'],
);
foreach( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => true );
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
$sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
}
$sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
foreach( $sizes as $size => $size_data ) {
$resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] );
if ( $resized )
$metadata['sizes'][$size] = $resized;
}
$attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $pid - for post_thumbnails*/);
if ( !is_wp_error( $id )) {
$attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_meta );
}
$final_temp_arr = array(
'pid' =>$pid,
'url' =>$file['url'],
'file'=>$file,
'attach_id'=>$attach_id
);
array_push($file_list, $final_temp_arr);
}
}
return $file_list;
}
In final, I using this function to get an array of information with attach-id variable that I inserting to repeater.
$att = my_update_attachment( 'msg-file-list' , $post_id );
$files_final_list = array();
foreach ($att as $key => $val) {
array_push($files_final_list, $val['attach_id']);
}
$value_arr = array(
array(
"msg-author" => $user_name,
"msg-date" => $date,
"msg-read-check" => true,
"msg-cont" => $msg_cont,
'msg-file-list' => $files_final_list
)
);
update_field( 'test_file_list' , $files_final_list , $post_id );
I guess that mistake is in last part , where I trying to upload files to repeater. Can someone show me what I'am doing wrong? Thanks for helping.
My woocommerce are not listing orders with status 'wc-expired'. I tried adding the 'wc_order_statuses' filter, but it still does not work.
add_filter('wc_order_statuses', function ($order_statuses){
$order_statuses['wc-expired'] = _x( 'Expired', 'Order status', 'woocommerce' );
return $order_statuses;
});
Row in Table wp_posts
The Orders List in Admin
Create new order status. Sample:
function register_expired_order_status() {
register_post_status( 'wc-expired', array(
'label' => 'Expired',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Expired <span class="count">(%s)</span>', 'Expired <span class="count">(%s)</span>' )
) );
}
add_action( 'init', 'register_expired_order_status' );
function add_expired_to_order_statuses( $order_statuses ) {
$new_order_statuses = array();
// add new order status after processing
foreach ( $order_statuses as $key => $status ) {
$new_order_statuses[ $key ] = $status;
if ( 'wc-processing' === $key ) {
$new_order_statuses['wc-expired'] = 'Expired';
}
}
return $new_order_statuses;
}
add_filter( 'wc_order_statuses', 'add_expired_to_order_statuses' );
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',
);