Trigger Default values wordpress plugin on install - wordpress

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

Related

Product query results are not correct

I need a custom fields on the inventory tab that will be filled in with the zipcode as the location of the agent.
Armed with the references I got here, now I have that field.
what I want to ask is how to concatenate this meta data with woocommerce shortcode?
I think like :
['products limit="12" columns="4" zipcode="12345"]
where "12345" will be changing dynamically as needed (zipcode filled based on agent location).
I have tried to do something but it is not working properly.
Here's the full code.
function action_woocommerce_product_options_inventory_product_data_zipcode() {
woocommerce_wp_text_input( array(
'id' => '_zipcode',
'label' => __( 'Zipcode', 'woocommerce' ),
'description' => __( 'Please fill your zipcode.', 'woocommerce' ),
'desc_tip' => 'true',
'placeholder' => __( '12345', 'woocommerce' )
) );
}
add_action( 'woocommerce_product_options_inventory_product_data', 'action_woocommerce_product_options_inventory_product_data_zipcode' );
// Save zipcode
function action_woocommerce_admin_process_product_object_zipcode( $product ) {
// Isset
if ( isset( $_POST['_zipcode'] ) ) {
// Update
$product->update_meta_data( '_zipcode', sanitize_text_field( $_POST['_zipcode'] ));
}
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object_zipcode', 10, 1 );
Try put to shortcode products :
function filter_shortcode_atts_products_zipcode ( $out, $pairs, $atts, $shortcode) {
if ( isset ( $atts['zipcode'] ) && !empty($atts['zipcode']) ) {
$out['zipcode'] = true;
} else {
$out['zipcode'] = false;
}
return $out;
}
add_filter( 'shortcode_atts_products', 'filter_shortcode_atts_products_zipcode', 10, 4);
function filter_woocommerce_shortcode_products_query_zipcode( $query_args, $atts, $type) {
if ( $type == 'products' && $atts['zipcode'] ) {
// Meta query
$query_args['meta_query'] = array(
array(
'key' => '_zipcode',
'value' => $atts['zipcode'],
'compare' => 'LIKE',
)
);
}
return $query_args;
}
add_filter( 'woocommerce_shortcode_products_query', 'filter_woocommerce_shortcode_products_query_zipcode', 10, 3 );
On testing I tried :
['products limit="12" columns="4" zipcode="12345"]
shortcode has displayed the product but does not refer to the postal code in the short code ("12345") but to all products that have a postal code.
Can somebody help me?
Thank you
Something doesn't feel right about the shortcode attribute function. I think you're setting the attribute as true and therefore it's comparing anything "truthy." Maybe just try setting the true one as the zipcode, like this:
function filter_shortcode_atts_products_zipcode ( $out, $pairs, $atts, $shortcode) {
if ( isset ( $atts['zipcode'] ) && !empty($atts['zipcode']) ) {
$out['zipcode'] = $atts['zipcode'];
} else {
$out['zipcode'] = false;
}
return $out;
}
That way it'll return the zipcode if it exists, and false if it doesn't, which the query can then use for the comparison.

wp_localize_script is not accepting dynamic value

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

Add custom column to woocommerce report - csv

I've got a question - is it possible to add one more column (which will present data from custom field) to csv export file in woocommerce? all necessary data is stored for each order as meta_key: 'authors_income'. I have no idea how to make it. I've tried to adapt below code, but it doesnt work:
function wpg_add_columns($cols) {
$cols['wc_settings_tab_payment_method'] = __('Payment Method', 'mytheme');
return $cols;
}
add_filter('wpg_order_columns', 'wpg_add_columns');
This should work. Let me know this goes.
<?php
//Step 1: Add field to column
function wpg_add_columns($cols) {
$cols['wc_settings_tab_authors_income'] = __('Authors Income', 'mytheme');
return $cols;
}
add_filter('wpg_order_columns', 'wpg_add_columns');
//Step 2: Add same column to settings, so that it will appear in settings page.
function wpg_add_fields($settings) {
$settings['authors_income'] = array(
'name' => __( 'Authors Income', 'woocommerce-simply-order-export' ),
'type' => 'checkbox',
'desc' => __( 'Authors Income', 'woocommerce-simply-order-export' ),
'id' => 'wc_settings_tab_authors_income'
);
return $settings;
}
add_filter('wc_settings_tab_order_export', 'wpg_add_fields');
//Note: Notice that in above step, id attribute is identical to that of array key in step 1. ( wc_settings_tab_authors_income )
//Step 3: Add it to csv.
function csv_write( &$csv, $od, $fields ) {
if( !empty( $fields['wc_settings_tab_authors_income'] ) && $fields['wc_settings_tab_authors_income'] === true ){
$authors_income = get_post_meta( $od->id, 'authors_income', true );
array_push( $csv, $authors_income );
}
}
add_action('wpg_add_values_to_csv', 'csv_write', 10, 3);

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

WordPress update_post_meta is returning odd results

Problems with WordPress update_post_meta.
I have a function that should be updating _gravity_form_data. It works, but it is adding extra data for some reason. Here's the function:
Here is the function:
function wpufe_gravity_custom_video( $post_id ) {
if (isset( $_POST['custom_video'])) {
$custom_video = 'a:13:{s:2:"id";s:1:"2";s:13:"display_title";b:0;s:19:"display_description";b:0;s:25:"disable_woocommerce_price";s:2:"no";s:12:"price_before";s:0:"";s:11:"price_after";s:0:"";s:20:"disable_calculations";s:3:"yes";s:22:"disable_label_subtotal";s:2:"no";s:21:"disable_label_options";s:2:"no";s:19:"disable_label_total";s:2:"no";s:14:"label_subtotal";s:8:"Subtotal";s:13:"label_options";s:7:"Options";s:11:"label_total";s:5:"Total";}';
update_post_meta( $post_id, '_gravity_form_data', $custom_video );
}
}
add_action( 'wpuf_add_post_after_insert', 'wpufe_gravity_custom_video' );
add_action( 'wpuf_edit_post_after_update', 'wpufe_gravity_custom_video' );
It SHOULD be making _gravity_form_data have this content:
a:13:{s:2:"id";s:1:"2";s:13:"display_title";b:0;s:19:"display_description";b:0;s:25:"disable_woocommerce_price";s:2:"no";s:12:"price_before";s:0:"";s:11:"price_after";s:0:"";s:20:"disable_calculations";s:3:"yes";s:22:"disable_label_subtotal";s:2:"no";s:21:"disable_label_options";s:2:"no";s:19:"disable_label_total";s:2:"no";s:14:"label_subtotal";s:8:"Subtotal";s:13:"label_options";s:7:"Options";s:11:"label_total";s:5:"Total";}
Yet when it updates the _gravity_form_data field, its output is:
s:429:"a:13:{s:2:"id";s:1:"2";s:13:"display_title";b:0;s:19:"display_description";b:0;s:25:"disable_woocommerce_price";s:2:"no";s:12:"price_before";s:0:"";s:11:"price_after";s:0:"";s:20:"disable_calculations";s:3:"yes";s:22:"disable_label_subtotal";s:2:"no";s:21:"disable_label_options";s:2:"no";s:19:"disable_label_total";s:2:"no";s:14:"label_subtotal";s:8:"Subtotal";s:13:"label_options";s:7:"Options";s:11:"label_total";s:5:"Total";}";
Why is it adding the s:429:" in the beginning and then the extra "; at the end? And most importantly, how do I fix it? :)
Thanks so much!
UPDATE: Was suggested to serialize the data, so I did:
function wpufe_gravity_custom_video( $post_id ) {
if (isset( $_POST['custom_video'])) {
$gubcustom_video = array('id' => 2, 'display_title' => '', 'display_description' => '', 'disable_woocommerce_price' => 'no', 'price_before' => '', 'price_after' => '', 'disable_calculations' => 'yes', 'disable_label_subtotal' => 'no', 'disable_label_option' => 'no', 'disable_label_total' => 'no', 'label_subtotal' => 'Subtotal', 'label_options' => 'Options', 'label_total' => 'Total');
$gubvideodata = serialize($gubcustom_video);
update_post_meta( $post_id, '_gravity_form_data', $gubvideodata );
}
}
add_action( 'wpuf_add_post_after_insert', 'wpufe_gravity_custom_video' );
add_action( 'wpuf_edit_post_after_update', 'wpufe_gravity_custom_video' );
...and still get the incorrect data posted to mysql.
Is there a way to just insert that string I need to insert? That's all I want to do, is update the database with that text.
I can do this in phpMySql easily, just copy and paste the text and it works like a champ. That's the solution I'm hoping for. Thanks again!
It looks like a serialized array that you are trying to insert manually but you should insert it by serializing it using serialize function, for example:
$custom_video = array('id' => 2, 'display_title' => '');
$data = serialize($custom_video);
update_post_meta( $post_id, '_gravity_form_data', $data );
Also, try using following hook:
add_action( 'save_post', 'save_meta_data' );
function save_meta_data($post_id)
{
$custom_video = array('id' => 2, 'display_title' => '');
$data = serialize($custom_video);
update_post_meta( $post_id, '_gravity_form_data', $data );
}
Problem solved. WP User Frontend Pro was setting the meta key with its own value of "1", causing it to re-serialize the serialized string. Problem solved by removing the WPUF meta key and just leaving the field.

Resources