wp_localize_script is not accepting dynamic value - wordpress

*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' );
......
}

Related

ACF Dynamic select values not showing data

This question makes me crazy for almost 2 weeks. I know I am not expert in Wordpress, so I am seeking for help here.
I have create a href that when user click it will go to new page.
Add Class2
This href post the Post id. Url display:
[http://localhost/dev6/create-class/?post=289][1]
create-class page:
At create-class page,I am using GET method to display post id from url
$post = $_GET['post'];
I have acf form in create-class page for create new post. In this form, there have dynamic select field but the select field not display any data.
<?php acf_form(array(
'post_id' => 'new_post',
'field_groups' => array(150),
'post_title' => false,
'post_content' => false,
'new_post' => array(
'post_type' => 'classes',
'post_status' => 'publish',
),
'return' => '%post_url%',
'submit_value' => 'Submit',
//'updated_message' => 'Course Submit!',
)); ?>
in my function.php I create function for dynamic select:
function acf_load_t_first_name2_field_choices($field) {
global $post;
//$post = $_GET['post'];
// reset choices
$field['choices'] = array();
// get the textarea value from options page without any formatting
$choices = get_field('t_first_name',$post->ID);
// loop through array and add to field 'choices'
if( is_array($choices) ) {
foreach( $choices as $choice ) {
$field['choices'][ $choice ] = $choice;
}
}
// return the field
return $field;
}
add_filter('acf/load_field/name=t_first_name2', 'acf_load_t_first_name2_field_choices');
Is there something wrong with my code?
I don't believe this will work in your create-class template:
$post = $_GET['post'];
You will need to set something like this up in your functions.php file:
function custom_query_vars_filter($vars) {
$vars[] .= 'post';
return $vars;
}
add_filter( 'query_vars', 'custom_query_vars_filter' );
Then, in your create-class template you can get the variable from the URL like this:
$post = get_query_var('post');
See if that gets you going in the right direction.

wp_list_comments function not working in wordpress 4.3.16 version

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
}

Template Overriding using a customization section

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)!

How do you target a specific page in Wordpress functions.php?

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

Trigger Default values wordpress plugin on install

I spent so much time to figure this out. How do automatically fill defaults values on the field or inserted into database upon installing the plugin.
I have tried these following codes but nothing works:
register_activation_hook(__FILE__, 'just_a_handler');
function just_a_handler($plugin_options) {
$defaults = array(
'youtube_keyword' => 'keyword here',
'youtube_author' => 'author here',
'youtube_content' => 'by_keyword',
'youtube_width' => '500',
'youtube_height' => '350',
'youtube_number_of_videos' => '5',
'youtube_preview' => '',
);
$plugin_options = wp_parse_args(get_option('youtube_plugin_options'), $defaults);
}
and this one:
register_activation_hook(__FILE__, 'just_a_handler');
function just_a_handler() {
add_option("youtube_keyword", 'keyword here', '', 'yes');
add_option("youtube_author", 'author here', '', 'yes');
}
To automatically fill an option with some defaults you can do something like the following. Depending on when you execute this code, I think it's a good idea to check that the option doesn't already exist before filling it with the default data. Also keep in mind that if you're storing an array, you need to serialize your data before adding it to the database. Databases can only store numbers, text, and dates. Serialization takes an array and turns it into a serialized string.
function init_options() {
$retrieved_options = array();
$defaults = array(
'youtube_keyword' => 'keyword here',
'youtube_author' => 'author here',
'youtube_content' => 'by_keyword',
'youtube_width' => '500',
'youtube_height' => '350',
'youtube_number_of_videos' => '5',
'youtube_preview' => '',
);
// Check to see if the option exists
$retrieved_options = maybe_unserialize( get_option( 'youtube_plugin_options' ) );
if ( $retrieved_options == '' ) {
// There are no options set
add_option( 'youtube_plugin_options', serialize( $defaults ) );
} elseif ( count( $retrieved_options ) == 0 ) {
// All options are blank
update_option( 'youtube_plugin_options', serialize( $defaults ) );
}
}
register_activation_hook( __FILE__, 'init_options' );

Resources