WordPress CMB2 - Get Option Value - wordpress

I am using the example from the CMB2 snippets library to add a theme options page in WordPress
/**
* Hook in and register a metabox to handle a theme options page and adds a menu item.
*/
function yourprefix_register_main_options_metabox() {
/**
* Registers main options page menu item and form.
*/
$args = array(
'id' => 'yourprefix_main_options_page',
'title' => 'Main Options',
'object_types' => array( 'options-page' ),
'option_key' => 'yourprefix_main_options',
'tab_group' => 'yourprefix_main_options',
'tab_title' => 'Main',
);
// 'tab_group' property is supported in > 2.4.0.
if ( version_compare( CMB2_VERSION, '2.4.0' ) ) {
$args['display_cb'] = 'yourprefix_options_display_with_tabs';
}
$main_options = new_cmb2_box( $args );
/**
* Options fields ids only need
* to be unique within this box.
* Prefix is not needed.
*/
$main_options->add_field( array(
'name' => 'Site Background Color',
'desc' => 'field description (optional)',
'id' => 'bg_color',
'type' => 'colorpicker',
'default' => '#ffffff',
) );
/**
* Registers secondary options page, and set main item as parent.
*/
$args = array(
'id' => 'yourprefix_secondary_options_page',
'menu_title' => 'Secondary Options', // Use menu title, & not title to hide main h2.
'object_types' => array( 'options-page' ),
'option_key' => 'yourprefix_secondary_options',
'parent_slug' => 'yourprefix_main_options',
'tab_group' => 'yourprefix_main_options',
'tab_title' => 'Secondary',
);
// 'tab_group' property is supported in > 2.4.0.
if ( version_compare( CMB2_VERSION, '2.4.0' ) ) {
$args['display_cb'] = 'yourprefix_options_display_with_tabs';
}
$secondary_options = new_cmb2_box( $args );
$secondary_options->add_field( array(
'name' => 'Test Radio',
'desc' => 'field description (optional)',
'id' => 'radio',
'type' => 'radio',
'options' => array(
'option1' => 'Option One',
'option2' => 'Option Two',
'option3' => 'Option Three',
),
) );
/**
* Registers tertiary options page, and set main item as parent.
*/
$args = array(
'id' => 'yourprefix_tertiary_options_page',
'menu_title' => 'Tertiary Options', // Use menu title, & not title to hide main h2.
'object_types' => array( 'options-page' ),
'option_key' => 'yourprefix_tertiary_options',
'parent_slug' => 'yourprefix_main_options',
'tab_group' => 'yourprefix_main_options',
'tab_title' => 'Tertiary',
);
// 'tab_group' property is supported in > 2.4.0.
if ( version_compare( CMB2_VERSION, '2.4.0' ) ) {
$args['display_cb'] = 'yourprefix_options_display_with_tabs';
}
$tertiary_options = new_cmb2_box( $args );
$tertiary_options->add_field( array(
'name' => 'Test Text Area for Code',
'desc' => 'field description (optional)',
'id' => 'textarea_code',
'type' => 'textarea_code',
) );
}
add_action( 'cmb2_admin_init', 'yourprefix_register_main_options_metabox' );
/**
* A CMB2 options-page display callback override which adds tab navigation among
* CMB2 options pages which share this same display callback.
*
* #param CMB2_Options_Hookup $cmb_options The CMB2_Options_Hookup object.
*/
function yourprefix_options_display_with_tabs( $cmb_options ) {
$tabs = yourprefix_options_page_tabs( $cmb_options );
?>
<div class="wrap cmb2-options-page option-<?php echo $cmb_options->option_key; ?>">
<?php if ( get_admin_page_title() ) : ?>
<h2><?php echo wp_kses_post( get_admin_page_title() ); ?></h2>
<?php endif; ?>
<h2 class="nav-tab-wrapper">
<?php foreach ( $tabs as $option_key => $tab_title ) : ?>
<a class="nav-tab<?php if ( isset( $_GET['page'] ) && $option_key === $_GET['page'] ) : ?> nav-tab-active<?php endif; ?>" href="<?php menu_page_url( $option_key ); ?>"><?php echo wp_kses_post( $tab_title ); ?></a>
<?php endforeach; ?>
</h2>
<form class="cmb-form" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="POST" id="<?php echo $cmb_options->cmb->cmb_id; ?>" enctype="multipart/form-data" encoding="multipart/form-data">
<input type="hidden" name="action" value="<?php echo esc_attr( $cmb_options->option_key ); ?>">
<?php $cmb_options->options_page_metabox(); ?>
<?php submit_button( esc_attr( $cmb_options->cmb->prop( 'save_button' ) ), 'primary', 'submit-cmb' ); ?>
</form>
</div>
<?php
}
/**
* Gets navigation tabs array for CMB2 options pages which share the given
* display_cb param.
*
* #param CMB2_Options_Hookup $cmb_options The CMB2_Options_Hookup object.
*
* #return array Array of tab information.
*/
function yourprefix_options_page_tabs( $cmb_options ) {
$tab_group = $cmb_options->cmb->prop( 'tab_group' );
$tabs = array();
foreach ( CMB2_Boxes::get_all() as $cmb_id => $cmb ) {
if ( $tab_group === $cmb->prop( 'tab_group' ) ) {
$tabs[ $cmb->options_page_keys()[0] ] = $cmb->prop( 'tab_title' )
? $cmb->prop( 'tab_title' )
: $cmb->prop( 'title' );
}
}
return $tabs;
}
This works great, but I can't figure out how to actually get one of these values and display it in a theme. Anyone have an example?

You can use cmb2_get_option()
It takes 3 parameters: cmb2_get_option( $option_key, $field_id, $default );
So in your case:
$option_key = yourprefix_main_options,
$field_id = bg_color,
$default = the default value (in case you set it).
It should look like this:
cmb2_get_option( 'yourprefix_main_options', 'bg_color' );
cmb2_get_option( 'yourprefix_secondary_options', 'radio' );
and so on ..
Also, You can use your own function with Fallback:
/**
* Wrapper function around cmb2_get_option
* #since 0.1.0
* #param string $key Options array key
* #param mixed $default Optional default value
* #return mixed Option value
*/
function myprefix_get_option( $key = '', $default = false ) {
if ( function_exists( 'cmb2_get_option' ) ) {
// Use cmb2_get_option as it passes through some key filters.
return cmb2_get_option( 'yourprefix_main_options', $key, $default );
}
// Fallback to get_option if CMB2 is not loaded yet.
$opts = get_option( 'yourprefix_main_options', $default );
$val = $default;
if ( 'all' == $key ) {
$val = $opts;
} elseif ( is_array( $opts ) && array_key_exists( $key, $opts ) && false !== $opts[ $key ] ) {
$val = $opts[ $key ];
}
return $val;
}
Use it like this:
myprefix_get_option( bg_color )

Please use the following code :
get_option("<your id>");
Like :
get_option('bg_color');
Hope this will work for you.

You can try using array system with get_option() function.
First time you need to use get_option('your-option-key');
like your option-key is "yourprefix_main_options" so you need to use get_option('yourprefix_main_options');
then you can keep your value on variable. like
$main_option_data = get_option('yourprefix_main_options');
then you can use $main_option_data and your filed id as a array. like your one filed id is bg_color so you can use $main_option_data['bg_color'];
You can check my one previous work, I think it will be help you.
// Theme Options
add_action( 'cmb2_admin_init', 'mosc_panel_theme_options_metabox' );
/**
* Hook in and register a metabox to handle a theme options page and adds a menu item.
*/
function mosc_panel_theme_options_metabox() {
/**
* Registers options page menu item and form.
*/
$mos_option_panel = new_cmb2_box( array(
'id' => 'mosc_theme_options_page',
'title' => esc_html__( 'Theme Options', 'cmb2' ),
'parent_slug' => 'themes.php', // Make options page a submenu item of the themes menu.
'object_types' => array( 'options-page' ),
'option_key' => 'mosc_theme_options', // The option key and admin menu page slug.
'icon_url' => 'dashicons-palmtree', // Menu icon. Only applicable if 'parent_slug' is left empty.
) );
// Regular text field
$mos_option_panel->add_field( array(
'name' => __( 'Contact Form Heading', 'mosc' ),
'id' => 'mosc-contact-form-heading',
'type' => 'text',
'default' => __('Feel free to drop me a line', 'mosc'),
) );
}
then I've used this code for show my field value.
$mosc_contact_heading = get_option('mosc_theme_options');
if(!empty($mosc_contact_heading['mosc-contact-form-heading'])) {
echo esc_html($mosc_contact_heading['mosc-contact-form-heading']);
}

I've used this code to show my field value and working perfectly:
echo cmb2_get_option( '_key_options', 'text_text');

Related

Add custom field to product inventory tab and display value on single product page where meta ends

I'm using the following code in my theme functions.php file to add a additional data field to the product inventory tab:
// Add Custom Field to woocommerce inventory tab for product
add_action('woocommerce_product_options_inventory_product_data', function() {
woocommerce_wp_text_input([
'id' => '_number_in_package',
'label' => __('Number of Pages', 'txtdomain'),
'type' => 'number',
]);
});
add_action('woocommerce_process_product_meta', function($post_id) {
$product = wc_get_product($post_id);
$num_package = isset($_POST['_number_in_package']) ? $_POST['_number_in_package'] : '';
$product->update_meta_data('_number_in_package', sanitize_text_field($num_package));
$product->save();
});
add_action('woocommerce_product_meta_start', function() {
global $post;
$product = wc_get_product($post->ID);
$num_package = $product->get_meta('_number_in_package');
if (!empty($num_package)) {
printf('<div class="custom-sku">%s: %s</div>', __('Number of Pages', 'txtdomain'), $num_package);
}
});
add_filter('woocommerce_product_data_tabs', function($tabs) {
$tabs['additional_info'] = [
'label' => __('Additional info', 'txtdomain'),
'target' => 'additional_product_data',
'class' => ['hide_if_external'],
'priority' => 25
];
return $tabs;
});
However, on the single product page, the custom field is added before category and ISBN. I want to place the custom field at the end after the product ISBN. Any advice?
Some comments/suggestions regarding your code attempt
To save fields you can use the woocommerce_admin_process_product_object hook, opposite the outdated woocommerce_process_product_meta hook
WooCommerce contains by default no ISBN field, but it looks like the woocommerce_product_meta_end hook will answer your question
So you get:
// Add custom field
function action_woocommerce_product_options_inventory_product_data() {
woocommerce_wp_text_input( array(
'id' => '_number_in_package',
'label' => __( 'Number of Pages', 'woocommerce' ),
'description' => __( 'This is a custom field, you can write here anything you want.', 'woocommerce' ),
'desc_tip' => 'true',
'type' => 'number'
) );
}
add_action( 'woocommerce_product_options_inventory_product_data', 'action_woocommerce_product_options_inventory_product_data' );
// Save custom field
function action_woocommerce_admin_process_product_object( $product ) {
// Isset
if ( isset( $_POST['_number_in_package'] ) ) {
// Update
$product->update_meta_data( '_number_in_package', sanitize_text_field( $_POST['_number_in_package'] ) );
}
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );
// Display on single product page
function action_woocommerce_product_meta_end() {
global $product;
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Get meta
$number = $product->get_meta( '_number_in_package' );
// NOT empty
if ( ! empty ( $number ) ) {
echo '<p>' . $number . '</p>';
}
}
}
add_action( 'woocommerce_product_meta_end', 'action_woocommerce_product_meta_end', 10 );

How to add custom field in shipping method using woocommerce wordpress

How to add custom field in shipping method using woocommerce wordpress
Please see my screenshot
Please try this code.
if ( ! function_exists( 'dimative_shipping_instance_form_fields_filters' ) ) {
/**
* Shipping Instance form add extra fields.
*
* #param array $settings Settings.
* #return array
*/
function dimative_shipping_instance_form_add_extra_fields( $settings ) {
$settings['shipping_extra_field_title'] = array(
'title' => esc_html__( 'Shipping method title', 'zincheco' ),
'type' => 'text',
'placeholder' => esc_html__( 'Please add shipping method title', 'zincheco' ),
'description' => '',
);
$settings['shipping_extra_field_description'] = array(
'title' => esc_html__( 'Shipping method description', 'zincheco' ),
'type' => 'textarea',
'placeholder' => esc_html__( 'Please add your shipping method description', 'zincheco' ),
'description' => '',
);
return $settings;
}
/**
* Shipping instance form fields.
*/
function dimative_shipping_instance_form_fields_filters() {
$shipping_methods = WC()->shipping->get_shipping_methods();
foreach ( $shipping_methods as $shipping_method ) {
add_filter( 'woocommerce_shipping_instance_form_fields_' . $shipping_method->id, 'dimative_shipping_instance_form_add_extra_fields' );
}
}
add_action( 'woocommerce_init', 'dimative_shipping_instance_form_fields_filters' );
}
In case if someone is looking how to get the value using #Өлзийбат-Нансалцог code example. I was able to retrieve it this way:
//Get Shipping rate object
//$method->id is the ID of the shipping method.
//In my case I used that in cart-shipping.php template
$WC_Shipping_Rate = new WC_Shipping_Rate($method->id);
// Returned value is flat_rate:1
$shipping_rate_id = $WC_Shipping_Rate->get_id();
//Replacing : with underscore to have the id in format of flat_rate_1
$shipping_rate_id = str_replace(':', '_', $shipping_rate_id);
//Get the description field value
//Since the value is stored inside options table use get_option() method
get_option('woocommerce_'.$shipping_rate_id.'_settings')['shipping_extra_field_description']
Here is the code for getting the value.
if ( ! function_exists( 'dimative_shipping_method_description' ) ) {
/**
* Function will print shipping method description.
*
* #param object $method Shipping method object.
* #param int $index Shipping method index.
* #return void
*/
function dimative_shipping_method_description( $method, $index ) {
$dimative_method_fields = get_option( 'woocommerce_' . $method->method_id . '_' . $method->instance_id . '_settings' );
$dimative_method_allowed_html = array(
'p' => array(
'class' => array(),
),
'strong' => array(),
'b' => array(),
'a' => array(
'href' => array(),
),
'span' => array(
'class' => array(),
),
);
// Shipping method custom description.
if ( $dimative_method_fields['shipping_extra_field_description'] ) {
?>
<div class="method-description"><?php echo wp_kses( $dimative_method_fields['shipping_extra_field_description'], $dimative_method_allowed_html ); ?></div>
<?php
}
}
add_action( 'woocommerce_after_shipping_rate', 'dimative_shipping_method_description', 1, 2 );
}

Woocommerce - Add custom checkout field to customer new account email

I am trying to display the "billing_gender" custom field I have added to my checkout form to the customer new account notification email.
The field is correctly saved to the database but it is shown empty in the new account email.
Other user meta fields (phone, ...) work but not my custom checkout field.
I guess it is saved to late in the user meta information but I really can't figure it out :
Here is my code :
functions.php
add_filter( 'woocommerce_checkout_fields' , 'divi_override_checkout_fields' );
function divi_override_checkout_fields( $fields ) {
unset($fields['billing']['billing_company']);
unset($fields['billing']['billing_address_1']);
unset($fields['billing']['billing_address_2']);
unset($fields['billing']['billing_city']);
unset($fields['billing']['billing_postcode']);
unset($fields['billing']['billing_state']);
unset($fields['billing']['billing_country']);
// Custom gender field
$fields['billing']['billing_gender'] = array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'label' => __( 'Title', 'divi-ultimate'),
'required' => true,
'priority' => 3,
'options' => array(
'' => __( 'Select title', 'divi-ultimate' ),
'male' => __( 'Mr', 'divi-ultimate' ),
'female' => __( 'Mrs', 'divi-ultimate' )
),
);
return $fields;
}
// Gender select default value
add_filter( 'default_checkout_billing_gender', 'checkout_billing_gender',10,2 );
function checkout_billing_gender($value) {
if ( is_user_logged_in()){
$current_user = wp_get_current_user();
$value = get_user_meta( $current_user->ID, 'billing_gender', true );
}
return $value;
}
//* Update the order meta with fields values
add_action('woocommerce_checkout_update_order_meta', 'divi_select_checkout_field_update_order_meta', 10, 2);
function divi_select_checkout_field_update_order_meta( $order_id ) {
if ($_POST['delivery-shop']) update_post_meta( $order_id, 'delivery-shop', esc_attr($_POST['delivery-shop']));
if ($_POST['billing_gender']) update_post_meta( $order_id, 'billing_gender', esc_attr($_POST['billing_gender']));
}
//* Update the user meta with gender value
add_action( 'woocommerce_checkout_update_user_meta', 'divi_save_extra_user_fields', 10, 2 );
function divi_save_extra_user_fields($customer_id) {
if (isset($_POST['billing_gender'])) {
update_user_meta( $customer_id, 'billing_gender', esc_attr($_POST['billing_gender']) );
}
}
What am I doing wrong ?
Cheers.
Here is the customer-new-account.php file :
$user = get_user_by('login', $user_login );
if (!empty($user)) {
$gender = get_user_meta($user->ID, 'billing_gender', true);
$lastname = $user->last_name;
$user_email = $user->user_email;
}
if( !empty($gender) && !empty($lastname) ) {
printf( esc_html__( 'Dear ' . $gender . ' %s,', 'woocommerce' ), esc_html( $lastname ) );
}
else {
printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $email ) );
} ?>

Display custom checkout field value on admin order detail section in Woocommerce

Hello I'm trying to display the custom checkout field in the admin order details page. My Custom field is Delivery Option and it allows the user to pick the to pick a value from checkbox. I use the code below following the similar topics about this, but it seems something is wrong with my code.
add_action( 'woocommerce_review_order_after_shipping', 'checkout_shipping_additional_field', 20 );
function checkout_shipping_additional_field()
{
$domain = 'wocommerce';
$default = 'option 1';
echo '<tr class="additional-shipping-fields"><th>' . __('Delivery Time', $domain) . '</th><td>';
// Add a custom checkbox field
woocommerce_form_field( 'custom_radio_field', array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'options' => array(
'option 1' => __('10:04 : 13:04 ', $domain),
),
'default' => $default,
), $default );
echo '</td></tr>';
}
//update order meta
add_action('woocommerce_checkout_update_order_meta', 'gon_update_order_meta_business_address');
function gon_update_order_meta_business_address( $order_id ) {
if ($_POST['custom_radio_field']) update_post_meta( $order_id, 'Business Address?',
esc_attr($_POST['custom_radio_field']));
}
// Display field value on the admin order edit page
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'custom_checkout_field_display_admin_order_meta', 10, 1 );
function custom_checkout_field_display_admin_order_meta( $order ){
$delivery_time = get_post_meta( $order->get_id(), 'Delivery Time', true );
if( ! empty( $delivery_time ) )
echo '<p><strong>'.__('Delivery Time', 'woocommerce').': </strong> ' . $delivery_time . '</p>';
}
There is some mistakes, so I have revisited your code. I have also replaced some hooks. Try the following:
// HERE set your the options array for your select field.
function delivery_time_options(){
$domain = 'woocommerce';
return array(
'1' => __('10:04 : 13:04 ', $domain),
'2' => __('14:04 : 16:04 ', $domain), // <== Added for testing
);
}
// Display a custom select field after shipping total line
add_action( 'woocommerce_review_order_after_shipping', 'checkout_shipping_additional_field', 20 );
function checkout_shipping_additional_field(){
$domain = 'woocommerce';
echo '<tr class="additional-shipping-fields"><th>' . __('Delivery Time', $domain) . '</th><td>';
// Add a custom select field
woocommerce_form_field( 'delivery_time', array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'options' => delivery_time_options(),
), '' );
echo '</td></tr>';
}
// Save custom field as order meta data
add_action('woocommerce_checkout_create_order', 'save_custom_field_order_meta', 22, 2 );
function save_custom_field_order_meta( $order, $data ) {
if ( isset($_POST['delivery_time']) ) {
$options = delivery_time_options(); // Get select options array
$option_key = esc_attr($_POST['delivery_time']); // The selected key
$order->update_meta_data( '_delivery_time', $options[$option_key] ); // Save
}
}
// Display a custom field value on the admin order edit page
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'display_custom_meta_data_in_backend_orders', 10, 1 );
function display_custom_meta_data_in_backend_orders( $order ){
$domain = 'woocommerce';
$delivery_time = $order->get_meta('_delivery_time');
if( ! empty( $delivery_time ) )
echo '<p><strong>'.__('Delivery Time', $domain).': </strong> ' . $delivery_time . '</p>';
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Based on #LoicTheAztec answer, if you want multiple fields without re-writing the functions for every field (DRY), you can use this class (by adding it to your functions.php):
/**
* Add a custom field to the woocommerce checkout page
* https://stackoverflow.com/q/52098807/
*/
class WOO_Add_Checkout_Field
{
public function __construct($options)
{
$this->field_name = $options['field_name'];
$this->label = $options['label'];
$this->placeholder = $options['placeholder'];
$this->required = $options['required'];
if ($this->field_name && $this->label && $this->placeholder) {
add_action('woocommerce_after_order_notes', [$this, 'customise_checkout_field']);
add_action('woocommerce_checkout_update_order_meta', [$this, 'custom_checkout_field_update_order_meta'], 10, 1);
add_action('woocommerce_admin_order_data_after_billing_address', [$this, 'display_custom_field_on_order_edit_pages'], 10, 1);
} else {
die("Error in WOO_Add_Checkout_Field \$options: \n\n" . var_dump($options));
}
}
public function customise_checkout_field($checkout)
{
echo '<div id="customise_checkout_field">';
// echo '<h2>' . __('Heading') . '</h2>';
woocommerce_form_field($this->field_name, array(
'type' => 'text',
'class' => array(
'my-field-class form-row-wide'
),
'label' => $this->label,
'placeholder' => $this->placeholder,
'required' => $this->required,
), $checkout->get_value($this->field_name));
echo '</div>';
}
public function custom_checkout_field_update_order_meta($order_id)
{
if (!empty($_POST[$this->field_name]))
update_post_meta($order_id, $this->field_name, $_POST[$this->field_name]);
else
update_post_meta($order_id, $this->field_name, 0);
}
public function display_custom_field_on_order_edit_pages($order)
{
$field = $order->get_meta($this->field_name);
if (!empty($field)) {
echo '<p><strong style="display:block" title="' . $this->placeholder . '">' . $this->label . ': </strong><span>';
echo $field;
echo '</span></p>';
}
}
}
And use it as many times as you'd like:
$my_custom_field_1 = new WOO_Add_Checkout_Field([
'field_name' => 'my_custom_field_1',
'label' => __('My First Field'),
'placeholder' => __('Please write something in field 1...'),
'required' => false,
]);
$my_custom_field_2 = new WOO_Add_Checkout_Field([
'field_name' => 'my_custom_field_2',
'label' => __('My Second Field'),
'placeholder' => __('Please write something in field 2...'),
'required' => false,
]);
$my_custom_field_3 = new WOO_Add_Checkout_Field([
'field_name' => 'my_custom_field_3',
'label' => __('My Third Field'),
'placeholder' => __('Please write something in field 3...'),
'required' => false,
]);
// and so on...
Please note:
The custom field will show up in admin area ONLY if it was not sent empty
You can customize this code how you like

Add custom post type template via plugin

I'm creating a plugin for a custom post type. I want to add a custom template for it. But I'm not sure how to add it via the plugin.
How can I add a custom post type template via the plugin?
Please help!
You can simply create and assign custom page templates for your custom post type in your custom plugin.
Just create 2 template file - single-{post_type}.php and archive-{post_type}.php - in a new templates sub-directory of your plugin directory.
Then add some code as per below example in your main plugin:
/*
* Set Page templates for CPT "your_cpt"
*/
add_filter( 'template_include', 'my_plugin_templates' );
function my_plugin_templates( $template ) {
$post_type = 'your_cpt'; // Change this to the name of your custom post type!
if ( is_post_type_archive( $post_type ) && file_exists( plugin_dir_path(__DIR__) . "templates/archive-$post_type.php" ) ){
$template = plugin_dir_path(__DIR__) . "templates/archive-$post_type.php";
}
if ( is_singular( $post_type ) && file_exists( plugin_dir_path(__DIR__) . "templates/single-$post_type.php" ) ){
$template = plugin_dir_path(__DIR__) . "templates/single-$post_type.php";
}
return $template;
}
Hope this example would be helpful for you.
Cheers !!
Below is a complete (blank) plugin that I put together based on my previously posted answer. I loaded it in my theme (based on twentyfifteen) and it works. Together with the plugin, as-is, you would also need The following file structure
- schs-blank/css schs-blank/js schs-blank/images
schs-blank/archive-blank.php schs-blank/single-blank.php
schs-blank/schs-blank-edit-posts.php
schs-blank/schs-blank-template.php
It should not be too tricky to figure out what should be in the above files, but for starters just put "<h1>{filename}</h1>" to see where each page is called.
<?php
/*
Plugin Name: SCHS Blank Plugin
Plugin URI: http://www.southcoasthosting.com/schs-blank
Tags: jquery, flyout, vertical, menu, animated, css, navigation, widget, plugin, scroll
Description: Creates a widget to place a vertical menu which caters for many menu items.
Author: Gavin Simpson
Version: 0.1
Author URI: http://www.southcoasthosting.com
074 355 1881
*/
class schs_blank
{
protected $plugin_slug;
private static $instance;
protected $templates;
public static function get_instance()
{
if( null == self::$instance )
{
self::$instance = new schs_blank();
}
return self::$instance;
}
private function __construct()
{
$this->templates = array();
$page_template = dirname( __FILE__ ) . '/schs-blank-template.php';
$this->templates = array('schs-blank-template.php' => 'SCHS Blank Page Template','schs-blank-edit-posts.php'=>'Edit Blank Post Template');
if(!is_admin())
{
add_action( 'wp_blank', array('schs_blank', 'header') );
}
else
add_action( 'wp_blank', array('schs_blank', 'footer') );
add_filter('page_attributes_dropdown_pages_args',array( $this, 'register_project_templates' ));
add_filter('wp_insert_post_data', array( $this, 'register_project_templates' ));
add_filter( 'template_include', array($this,'schs_force_template' ));
add_filter('template_include', array( $this, 'view_project_template') );
add_action('admin_menu', array($this,'setup_blank_admin_menus'));
add_action( 'init', array($this,'blank_custom_post' ));
}
function schs_force_template($template)
{
if( is_archive( 'blank' ) )
{
$template = WP_PLUGIN_DIR .'/'. plugin_basename( dirname(__FILE__) ) .'/archive-blank.php';
}
if( is_singular( 'blank' ) )
{
$template = WP_PLUGIN_DIR .'/'. plugin_basename( dirname(__FILE__) ) .'/single-blank.php';
}
return $template;
}
function header(){
wp_enqueue_script('jquery');
wp_enqueue_style( 'blank-css', schs_blank::get_plugin_directory() . "/css/blank.css" );
wp_enqueue_script('schs_blank', schs_blank::get_plugin_directory() . '/js/schs-blank.js', array('jquery'));
}
function footer()
{
}
function get_plugin_directory(){
return WP_PLUGIN_URL . '/schs-blank';
}
function setup_blank_admin_menus()
{
add_menu_page('SCHS Blank Settings', 'SCHS Blank Settings', 'manage_options',
'SCHS_blank_settings', array($this,'SCHS_page_settings'));
add_submenu_page('SCHS_blank_settings',
'SCHS Page Elements', 'Blank Topics', 'manage_options',
'SCHS_blank_topics_settings', array($this,'SCHS_blank_topics_settings'));
}
function SCHS_page_settings()
{
?>
<div class="wrap">
<h2>There are no Blank options at this stage.</h2>
</div>
<?php
}
function SCHS_blank_topics_settings()
{
?>
<div id="blank_topics" class="wrap">
<h1>There are no blank topics at this stage</h1>
</div>
<?php
}
function blank_custom_post()
{
$labels = array(
'name' => _x( 'Blank', 'post type general name' ),
'singular_name' => _x( 'Topic', 'post type singular name' ),
'add_new' => _x( 'Add New', 'book' ),
'add_new_item' => __( 'Add New Blank Topic' ),
'edit_item' => __( 'Edit Blank Topic' ),
'new_item' => __( 'New Blank Topic' ),
'all_items' => __( 'All Blank Topics' ),
'view_item' => __( 'View Blank Topics' ),
'search_items' => __( 'Search Blank Topics' ),
'not_found' => __( 'No blank topics found' ),
'not_found_in_trash' => __( 'No blank topics found in the trash' ),
'parent_item_colon' => '',
'menu_name' => 'Blank'
);
$args = array(
'labels' => $labels,
'description' => 'Holds our blank topic specific data',
'public' => true,
'menu_position' => 5,
'supports' => array( 'title', 'editor'),
'has_archive' => true,
'menu_icon' => $this->get_plugin_directory().'/images/blank-icon.png',
);
register_post_type( 'blank', $args );
flush_rewrite_rules();
}
public function register_project_templates( $atts )
{
// Create the key used for the themes cache
$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );
// Retrieve the cache list.
// If it doesn't exist, or it's empty prepare an array
$templates = wp_get_theme()->get_page_templates();
if ( empty( $templates ) ) {
$templates = array();
}
// New cache, therefore remove the old one
wp_cache_delete( $cache_key , 'themes');
// Now add our template to the list of templates by merging our templates
// with the existing templates array from the cache.
$templates = array_merge( $templates, $this->templates );
// Add the modified cache to allow WordPress to pick it up for listing
// available templates
wp_cache_add( $cache_key, $templates, 'themes', 1800 );
return $atts;
}
/**
* Checks if the template is assigned to the page
*/
public function view_project_template( $template )
{
global $post;
if (!isset($this->templates[get_post_meta(
$post->ID, '_wp_page_template', true
)] ) ) {
return $template;
}
$file = plugin_dir_path(__FILE__). get_post_meta(
$post->ID, '_wp_page_template', true
);
// Just to be safe, we check if the file exist first
if( file_exists( $file ) )
{
return $file;
}
else
{
echo $file;
exit;
}
return $template;
}
}
add_action( 'plugins_loaded', array( 'schs_blank', 'get_instance' ) );
?>
I hope this helps a bit more.
This work for me, kindly try it, Thanks
Templates is loaded into cpt file, which was located at
custom_plugin -> app -> cpt -> cpt_article.php
Template is located
custom_plugin -> app -> templates
add_filter( 'single_template', 'load_my_custom_template', 99, 1 );
function load_custom_templates($single_template) {
global $post;
if ($post->post_type == 'article' ) {
$single_template = trailingslashit( plugin_dir_path( __FILE__ ) .'app/templates' ).'single_article.php';
}
return $single_template;
}
You create a template file in your plugin, e.g /templates/myposttype-page.php
Then add below code into your plugin.
Change 'myposttype' to your post type
$custom_post_type = 'myposttype';
add_filter("theme_{$custom_post_type}_templates", "add_{$custom_post_type}_template");
add_filter('single_template', "redirect_{$custom_post_type}_template");
function add_myposttype_template() {
$templates['myposttype-page.php'] = 'My type Template';
return $templates;
}
function redirect_myposttype_template ($template) {
if( is_page_template('myposttype-page.php') ){
$template = plugin_dir_path(__FILE__). 'templates/myposttype-page.php';
}
return $template;
}

Resources