I am trying to override my default templates from customization section, I am using code to do that, but if I am using it I am unable to assign a template to the edit-page page, Can anyone give an idea how both the customization section and edit-page assign template work. I want to set the template when I am creating a page and after assigning it I want to override.
Consider I have a blog page, I want to assign it archive.php template and ten want to override It from customization section. There is the particular condition where I want it to work.
<?php
/**
* Adds the Customize page to Select template For Pages
*/
add_action( 'wp_footer', 'cur_page_template' );
function cur_page_template(){
var_dump( get_option('current_page_template') );
var_dump( get_page_template() );
exit;
}
function widgetsite_template_override($wp_customize){
$wp_customize->add_panel( 'template_options', array(
'title' => __( 'Template Options', 'widgetsite' ),
'description' => $description, // Include html tags such as <p>.
'priority' => 160, // Mixed with top-level-section hierarchy.
) );
$wp_customize->add_section('theme_template_override', array(
'title' => __('Override Templates', 'widgetsite'),
'panel' => 'template_options',
'description' => '',
'priority' => 120,
));
$templates = get_page_templates();
$cats = array();
$i = 0;
foreach($templates as $template_name => $template_file){
//$cats[$template_name] = $template_name;
if (strpos($template_file,'layouts') !== false) {
$cats[$template_file] = $template_name;
}
}
$wp_customize->add_setting('widgetsite_archive_template');
$wp_customize->add_setting('widgetsite_page_template');
$wp_customize->add_setting('widgetsite_index_template');
$wp_customize->add_setting('widgetsite_post_template');
$wp_customize->add_setting('widgetsite_search_template');
$wp_customize->add_control( 'widgetsite_archive_template', array(
'settings' => 'widgetsite_archive_template',
'label' => 'Override Archive Template:',
'section' => 'theme_template_override',
'type' => 'select',
'choices' => array_merge(array( "archive.php"=>get_option('current_page_template')), $cats)
));
$wp_customize->add_control( 'widgetsite_page_template', array(
'settings' => 'widgetsite_page_template',
'label' => 'Override Page Template:',
'section' => 'theme_template_override',
'type' => 'select',
'choices' => array_merge( array( "page.php" =>get_option('current_page_template')), $cats)
));
$wp_customize->add_control( 'widgetsite_index_template', array(
'settings' => 'widgetsite_index_template',
'label' => 'Override Index Template:',
'section' => 'theme_template_override',
'type' => 'select',
'choices' => array_merge(array( "index.php"=>get_option('current_page_template')), $cats)
));
$wp_customize->add_control( 'widgetsite_post_template', array(
'settings' => 'widgetsite_post_template',
'label' => 'Override Post Template:',
'section' => 'theme_template_override',
'type' => 'select',
'choices' => array_merge(array( "post.php"=>get_option('current_page_template')), $cats)
));
$wp_customize->add_control( 'widgetsite_search_template', array(
'settings' => 'widgetsite_search_template',
'label' => 'Override Search Template:',
'section' => 'theme_template_override',
'type' => 'select',
'choices' => array_merge(array( "search.php"=>get_option('current_page_template')), $cats)
));
}
add_action('customize_register', 'widgetsite_template_override');
$theme_mode_templates['archive.php'] = get_theme_mod("widgetsite_archive_template");
$theme_mode_templates['page.php'] = get_theme_mod("widgetsite_page_template");
$theme_mode_templates['index.php'] = get_theme_mod("widgetsite_index_template");
$theme_mode_templates['post.php'] = get_theme_mod("widgetsite_post_template");
$theme_mode_templates['search.php'] = get_theme_mod("widgetsite_search_template");
function widgetsite_template_redirect($template){
global $wp_query;
global $post;
$cur= basename($template);
if( $cur === 'page.php' && get_theme_mod("widgetsite_page_template")){ //note $cur will never be empty!
$template= get_template_directory() . '/' . get_theme_mod("widgetsite_page_template");// assuming this will return correct template...
//if issues try hardcoding a path to test...
}
if( $cur === 'archive.php' && get_theme_mod("widgetsite_archive_template")){ //note $cur will never be empty!
$template= get_template_directory() . '/' . get_theme_mod("widgetsite_archive_template");// assuming this will return correct template...
//if issues try hardcoding a path to test...
}
if( $cur === 'index.php' && get_theme_mod("widgetsite_index_template")){ //note $cur will never be empty!
$template= get_template_directory() . '/' . get_theme_mod("widgetsite_index_template");// assuming this will return correct template...
//if issues try hardcoding a path to test...
}
if( $cur === 'post.php' && get_theme_mod("widgetsite_post_template")){ //note $cur will never be empty!
$template= get_template_directory() . '/' . get_theme_mod("widgetsite_post_template");// assuming this will return correct template...
//if issues try hardcoding a path to test...
}
if( $cur === 'search.php' && get_theme_mod("widgetsite_search_template")){ //note $cur will never be empty!
$template= get_template_directory() . '/' . get_theme_mod("widgetsite_search_template");// assuming this will return correct template...
//if issues try hardcoding a path to test...
}
return $template;
}
add_filter( 'template_include', 'widgetsite_template_redirect', 99 );
How the choose template box works from post edit screen.
It is important to remember pages are also posts and all meta relating to posts are stored in the post meta table. Page post types differ slightly from the standard post types as they do not follow the single-postname.php template use function. Instead pages save the template file path in the wp_postmeta database table with a key of _wp_page_template.
So one option to change this value is to change it after save post.
function save_template_file( $post_id ) {
if ( 'page' != $post->post_type ) {
return;
}
//insert logic here
$filelocation= 'anywhere.....';
update_post_meta($post_id, '_wp_page_template', $filelocation);
}
add_action('save_post', 'save_template_file', 11 );
Now this is not what you are looking for, but you mentioned you wanted to understand the process, so for pages, wp will reference the template file from post meta and pull this value. So you can change it after saving if it will always follow the same logic (slightly optimized the process). This is the file that shows up in the edit post screen and will always pull the db value unless wp tries to load the template and realizes it does not exist anymore, in which case it reverts to the defaults file in the select box.
The filter template_include is within the function that searches for the correct template for the pages post type (other post types have the filter single_template)
Your use of include here is incorrect. Don't forget a filter will expect a value returned to work correctly in this case $template.
So if we want to change the template for pages....
add_filter('template_include', 'assign_new_template');
function assign_new_template ($template){
//we already have a template name, no need to pull it again..
$cur= basename($template);
if( $cur === 'page.php' && get_theme_mod("widgetsite_page_template")){ //note $cur will never be empty!
$template= get_template_directory() . '/layouts/' . get_theme_mod("widgetsite_page_template");// assuming this will return correct template...
//if issues try hardcoding a path to test...
}
// dont need a else, we will only change the template if our logic is satisfied...
// etc
return $template;
}
Setting the selects
You are missing the value for default so i propose the following mod as i cant see what your setting in get_option('current_page_template') but if there is a correct filename there replace page.php with it.
While you are not setting a default value for your select box, your page will render the 1st value of the select if none are marked selected so it should work the same.
$wp_customize->add_control( 'widgetsite_search_template', array(
'settings' => 'widgetsite_search_template',
'label' => 'Override Search Template:',
'section' => 'theme_template_override',
'type' => 'select',
'choices' => array_merge(array("page.php"=>'default'), $cats)
));
If you resave all the options like above it should be working (it was for me)!
Related
*Context
I am new to WordPress plugin development and I have just started developing one. Which is basically a blog slider plugin. The concept is very simple. The user can use shortcodes with parameters to determine which posts and how many posts to be shown. There is no admin settings page for changing the appearance of the slider though, but I'll work on that. The user have to use shortcode whenever the slider is needed.
The development part is also simple. I am checking the parameters that the user passes through the shortcode. And then a query runs and returns an array of posts and then displays the structure. Very simple.
*Problem
Now I am trying to make the plugin options more dynamic (via shortcode) i.e. the user can control whether the slider should auto-play or not, loop should be enabled or not, pause on hover, dots/nav hide or show etc. I am using owl carousel for this slider. So that means I have to change the attributes of the slider in JavaScript file.
The basic idea is to take the parameters from function's $atts array, and pass it to the JavaScript file. I know this can be accomplished using wp_localize_script, but I cannot figure out how.
Here is my code to make things more clear.
mainfile.php
add_shortcode( 'sp-slider', 'sp_slider_get_posts');
function sp_slider_get_posts( $atts ) {
$values = shortcode_atts( array(
'number' => '-1',
'category-id' => '', //DEFAULT VALUE null, WILL BE REPLACED ONCE USER DECLARES IN SHORTCODE
'category-name' => '',
'orderby' => '',
'order' => '',
'include-posts' => '',
'exclude-posts' => '',
'author-id' => '',
'author-name' => '',
'autoplay' => ''
), $atts );
if( !empty($values['number']) ||
!empty($values['category-id']) ||
!empty($values['category-name']) ||
!empty($values['orderby']) ||
!empty($values['order']) ||
!empty($values['include-posts']) ||
!empty($values['exclude-posts']) ||
!empty($values['author-id']) ||
!empty($values['author-name']) ||
!empty($values['autoplay'])) {
$args = array(
'numberposts' => $values['number'],
'cat' => $values['category-id'],
'category_name' => $values['category-name'],
'orderby' => $values['orderby'],
'order' => $values['order'],
'include' => $values['include-posts'],
'exclude' => $values['exclude-posts'],
'meta_key' => '',
'meta_value' => '',
'post_parent' => '',
'author' => $values['author-id'],
'author_name' => $values['author-name'],
'post_status' => 'publish',
'suppress_filters' => true,
'fields' => '',
);
$autoplay = $values['autoplay']; //GET AUTOPLAY VALUE. NO IDEA HOW TO USE IT. SO I TRIED THE FOLLOWING
// THE FOLLOWING FUNCTION HOLDS THE wp_localize_script FUNCTION, WHICH IS DECLARED AT THE END OF THIS CURRENT FUNCTION sp_slider_get_posts.
sp_carousel_settings($autoplay); //PASSING THE USER INPUT
$posts_array = get_posts( $args );
if( !empty( $posts_array ) ) {
$output = "<div class='sp-slider-wrapper'>";
$output .= '<div class="owl-carousel owl-theme">';
foreach( $posts_array as $post ) {
include( "includes/inc_slider_section.php"); // ALL THE SLIDER STRUCTURE IS IN DIFFERENT FILE WHICH IS INCLUDED HERE
}
$output .="</div>";
$output .="</div>";
}
return $output;
}
}
// HERE IS sp_carousel_settings() DECLARATION
function sp_carousel_settings( $autoplay ) {
$carousel_settings = array( 'autoplay' => $autoplay);
wp_localize_script( 'sp_main_js', 'carousel_settings', $carousel_settings );
}
add_action( 'wp_enqueue_scripts', 'sp_carousel_settings' );
mainjs.js
$(document).ready(function() {
...
...
var autoplay= '';
if(typeof carousel_settings !== 'undefined') {
autoplay = carousel_settings.autoplay;
}
else {
autoplay = false;
}
$('.owl-carousel').owlCarousel({
loop:true,
autoplay:autoplay,
autoplayTimeout:2000,
autoplayHoverPause:true,
...
...
}
})
This doesn't work. Here I would like to mention that, in add_action() function, if i put wp_footer instead of wp_enqueue_scripts, it adds the script to the footer of the page (I have checked it by viewing the source) but the autoplay value is null.
Another thing i would mention is that, in sp_carousel_settings() function, instead of passing the $autoplay variable, if I write any static value like this $carousel_settings = array( 'autoplay' => true);, it works.
*I tried echoing out $autoplay inside sp_carousel_settings() and it prints the value! But does not get to the js file.
*I tried checking the value of $autoplay and pass a hardcore sting inside wp_localize_script like
function sp_carousel_settings( $autoplay ) {
if( $autoplay == "true" ) {
echo "Inside!!!";
$carousel_settings = array( 'autoplay' => true);
}
else {
echo "Outside!!!";
$carousel_settings = array( 'autoplay' => false);
}
wp_localize_script( 'sp_main_js', 'carousel_settings', $carousel_settings );
}
add_action( 'wp_footer', 'sp_carousel_settings' );
Does not work. EVEN it prints out "Inside!!!" but does not pass true in autoplay. The value is always false.
*I have registered the js file in the beginning of the plugin, where the plugin activates and gets initialized. Like this
function sp_slider_include_css_js() {
...
...
wp_register_script('sp_main_js', plugins_url('assets/js/main.js',__FILE__));
wp_enqueue_script('sp_main_js');
...
...
}
add_action( 'wp_footer','sp_slider_include_css_js');
*I have searched internet for help but was unable to find. Any reference will be appreciated.
*I know that I might be using the function in an improper way. I am clueless (and new to this).
Have to do some changes like,
Step 1:
function sp_carousel_settings() {
wp_register_script( 'sp_main_js', 'you/file/path/here', array( 'jquery' ), '1.0', true);
}
add_action( 'wp_enqueue_scripts', 'sp_carousel_settings' );
Step 2:
add_shortcode( 'sp-slider', 'sp_slider_get_posts');
function sp_slider_get_posts( $atts ) {
.....
$carousel_settings = array( 'autoplay' => $autoplay);
wp_localize_script( 'sp_main_js', 'carousel_settings', $carousel_settings );
wp_enqueue_script( 'sp_main_js' );
......
}
I am adding load more comments button in comments section. i want load function wp_list_comments using Ajax, function are loading but wp_list_comment not display in wordpress 4.3.16 version. How to solve this problem???
My code are is:
// maybe it isn't the best way to declare global $post variable, but it is simple and works perfectly!
add_action('wp_ajax_cloadmore', 'misha_comments_loadmore_handler');
add_action('wp_ajax_nopriv_cloadmore', 'misha_comments_loadmore_handler');
function misha_comments_loadmore_handler(){
global $post;
$post = get_post( $_POST['post_id'] );
setup_postdata( $post );
// actually we must copy the params from wp_list_comments() used in our theme
wp_list_comments( array(
'page' => $_POST['cpage'], // current comment page
'per_page' => get_option('comments_per_page'),
'style' => '<div>', // comments won't wrapped in this tag and it is awesome!
'short_ping' => true,
) );
die; // don't forget this thing if you don't want "0" to be displayed
}
Try this code.
add_action('wp_ajax_cloadmore', 'misha_comments_loadmore_handler');
add_action('wp_ajax_nopriv_cloadmore', 'misha_comments_loadmore_handler');
function misha_comments_loadmore_handler(){
$comments = get_comments(array(
'post_id' => $_POST['post_id'],
'status' => 'approve'
));
wp_list_comments(array(
'page' => $_POST['cpage'], // current comment page
'per_page' => get_option('comments_per_page'),
'style' => '<div>', // comments won't wrapped in this tag and it is awesome!
'short_ping' => true,
), $comments);
die; // don't forget this thing if you don't want "0" to be displayed
}
I'm adding custom special fields to the checkout page through
add_filter('woocommerce_checkout_fields', custom_woocommerce_checkout_fields');
function custom_woocommerce_checkout_fields(){
... //other code
$fields = array("field_1", ..., "field_n"); //pseudocode
foreach ($fields as $key => $field) {
$class = $i % 2 == 0 ? array('form-row-first') : array('form-row-last');
woocommerce_form_field($key, array(
'type' => 'text',
'class' => $class,
'label' => $labels[$i],
'placeholder' => __('placeholder cm', 'woothemes'),
'validate' => false,
'required' => true,
'custom_attributes' => array('disabled' => true)
), $field);
$i++;
}
}
and it works perfectly. My goal is now to save this information to the user meta once he concludes the order whether is already registered or not.
To achieve this I'm using
add_action('woocommerce_checkout_update_user_meta','checkout_update_user_fields');
function checkout_update_user_fields($user_id){
if($user_id){
foreach ($fields as $field) { //the fields are the same as before
if (!empty($_POST[$field])) {
update_user_meta($user_id, $field, sanitize_text_field($_POST[$field]));
}
}
}
}
The issue is that the $_POST variable does not contain the custom fields that I inserted inside the checkout form.
Why is this happening? How can I achieve this?
I feel like the most stupid man in the world; disabled input are not posted.
Hope this will save time to someone
I am currently using the Multi Post Thumbnails plugin for Wordpress, but I only want the extra thumbnails provided by the plugin to show on one specific page. The plugin does not appear to natively support this functionality but it seems like something that would be pretty easy to add, I'm just not sure of the right way to go about it as I'm fairly new to Wordpress development.
The code for Multi Post Thumbnails is the following, which simply goes in functions.php:
if (class_exists('MultiPostThumbnails')) {
new MultiPostThumbnails(
array(
'label' => 'Secondary Image',
'id' => 'secondary-image',
'post_type' => 'page'
)
);
new MultiPostThumbnails(
array(
'label' => 'Tertiary Image',
'id' => 'tertiary-image',
'post_type' => 'page'
)
);
}
It seems to me it would just be a simple case of wrapping this in a check so that it only runs for a specific page ID, but I'm not quite sure how to go about doing that.
This is probably somewhat of a hack. To my knowledge post/page id's are not accessible from inside functions.php.
// get the id of the post/page based on the request uri.
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$post_id = url_to_postid($url);
// the id of the specific page/post.
$specific_post_id = 3;
// check if the requested post id is identical to the specific post id.
if ($post_id == $specific_post_id) {
if (class_exists('MultiPostThumbnails')) {
new MultiPostThumbnails(
array(
'label' => 'Secondary Image',
'id' => 'secondary-image',
'post_type' => 'page'
)
);
new MultiPostThumbnails(
array(
'label' => 'Tertiary Image',
'id' => 'tertiary-image',
'post_type' => 'page'
)
);
}
}
This is also probably a hack but it worked for me. I got stung by the AJAX 'post_id' back to the admin page once the image has been selected. My usage was for a slug but the function could easily be modified for a post ID.
function is_admin_edit_page( $slug ){
if( ( isset($_GET) && isset($_GET['post']) ) || ( isset($_POST) && isset($_POST['post_id']) ) )
{
$post_id = 0;
if(isset($_GET) && isset($_GET['post']))
{
$post_id = $_GET['post'];
}
else if(isset($_POST) && isset($_POST['post_id']))
{
$post_id = $_POST['post_id'];
}
if($post_id != 0)
{
$c_post = get_post($post_id);
if( $c_post->post_name == $slug )
{
return true;
}
}
}
return false;
}
if( is_admin_edit_page('work') ) {
new MultiPostThumbnails(
array(
'label' => 'Hero 1 (2048px x 756px JPEG)',
'id' => 'am-hero-1',
'post_type' => 'page'
)
);
}
I am making front end admin for users to add/edit their posts. I already made post add form and it works, but edit form doesnt work.
functions.php
function add_new_post( $post_id )
{
if( $post_id == 'new' ) {
// Create a new post
$post = array(
'post_title' => $_POST["fields"]['field_52c810cb44c7a'],
'post_category' => array(4),
'post_status' => 'draft',
'post_type' => 'post'
);
// insert the post
$post_id = wp_insert_post( $post );
return $post_id;
}
else {
return $post_id;
}
}add_filter('acf/pre_save_post' , 'add_new_post' );
index.php
<div id="updateform-<?php the_ID(); ?>" class="collapse">
<?php
echo get_the_ID();
$args = array(
'post_id' => get_the_ID(), // post id to get field groups from and save data to
'field_groups' => array(31), // this will find the field groups for this post (post ID's of the acf post objects)
'form' => true, // set this to false to prevent the <form> tag from being created
'form_attributes' => array( // attributes will be added to the form element
'id' => 'post',
'class' => '',
'action' => get_permalink( get_the_ID() ),
'method' => 'post',
),
'return' => add_query_arg( 'updated', 'true', get_permalink() ), // return url
'html_before_fields' => '', // html inside form before fields
'html_after_fields' => '', // html inside form after fields
'submit_value' => 'Update', // value for submit field
'updated_message' => 'Post updated.', // default updated message. Can be false to show no message
);
acf_form( $args );
?>
</div>
For saving posts you should use save_post not pre_save_post.
Basically pre_save_post is used for new posts.
Use this below add_filter('save_post' , 'add_new_post');
I created plugins for that:
Forms actions
https://wordpress.org/plugins/forms-actions/
Add actions to yours ACF forms.
ACF Frontend display
https://wordpress.org/plugins/acf-frontend-display/
Display your ACF form on frontend
If by some chance you happen to be using Elementor Page Builder, you can do this by installing Advanced Widgets for Elementor. It comes with an ACF Form widget that you can just drag & drop anywhere into your site and configure your form through the UI (no coding required).