I want to upload multiple images using wordpress.
Here is my code which is using to single upload
if ( ! function_exists( 'wp_handle_upload' ) )
require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['photo'];
$upload_overrides = array( 'test_form' => FALSE );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
echo "File is valid, and was successfully uploaded.\n";
var_dump( $movefile);
}
else {
echo "Possible file upload attack!\n";
}
How I can upload multiple images using wordpress?
Try to implement like this:
$files = $_FILES['photo'];
foreach ($files['photo'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
wp_handle_upload($file);
}
}
You might be able to achieve what you're trying to do easier by using the native WordPress Media Uploader.
I had a good resource bookmarked at one point but can't seem to find it. I ran into a situation a few months ago that required the same thing. This is what I ended up doing:
Loading the WordPress image scripts into the beginning of my PHP script:
require_once( ABSPATH . 'wp-admin/includes/image.php' );
Then you can call the uploader on element click using jQuery like this:
jQuery(document).ready(function($) {
// Define a variable to be used to store the frame data
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = 999; // Set this
$('#upload_button').live('click', function( event ){
element = $(this);
event.preventDefault();
// If the media frame already exists, reopen it.
if (file_frame) {
// Set the post ID to what we want
file_frame.uploader.uploader.param('post_id', set_to_post_id);
// Open frame
file_frame.open();
return;
} else {
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: $(this).data('uploader_title'),
button: {
text: $(this).data('uploader_button_text'),
},
multiple: true // Set to false to allow only one file to be selected
});
// When an image(s) have been selected, run a callback.
file_frame.on('select', function() {
// Do something if necessary
function_to_fire();
});
// Finally, open the modal
file_frame.open();
});
});
There is an attachment object passed to the callback function which will contain all of the IDs and such for the attachments uploaded.
The set_to_post_id is the id of the post/page you want to "attach" the media to. If you're not trying to attach them to a post, you shouldn't need to worry about this and some of the above code will not apply.
Related
Is there a hook that I can use to change the customer column heading to the company name?
As mentioned in the comments there are no hooks you can use here as the Analytics pages are rendered via JavaScript.
The code snippet below will add a mutation observer checking if the table on the order analytics page is changing (as these headers are being added dynamically via JavaScript). Each time a change (mutation) is registered it checks for the 'Customer' header. If it is found it is changed to 'Company name'. Perhaps not the most elegant solution but it does work.
add_action( 'admin_footer', 'woocommerce_analytics_change_customer_header' );
function woocommerce_analytics_change_customer_header() {
if ( isset( $_GET['page'] ) && isset( $_GET['path'] ) ) {
if ( $_GET['page'] == 'wc-admin' && $_GET['path'] == '/analytics/orders' ) {
?>
<script>
jQuery( function( $ ) {
// select the target node
var target = document.querySelector('#woocommerce-layout__primary');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if ( $('th.woocommerce-table__header').length ) {
$('th.woocommerce-table__header').each(function(){
let $label = $(this).find('span');
if ( $label.text() == 'Customer' ) {
$label.text('Company name');
}
});
}
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true, subtree: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
});
</script>
<?php
}
}
}
This code snippet should be added to the functions.php of your child theme or via a plugin like Code Snippets.
I have a shortcode that generates a gallery, given the gallery ID.
function rb_scroll_gallery_shortcode( $atts, $content ) {
$a = shortcode_atts( array(
'id' => -1,
), $atts );
$gallery_ID = $a['id'];
$output = '';
if($gallery_ID != -1){
ob_start();
$gallery = new RB_Scroll_Gallery($gallery_ID);
$gallery->render();
$output = ob_get_clean();
}
return $output;
}
add_shortcode( 'rb_scroll_gallery', 'rb_scroll_gallery_shortcode' );
Now, I've made a Gutenberg block that works perfectly in the editor. You can select a gallery and it will save. However, I dont want to repeat code and have the html in the save property and in the php code.
So I was wondering if there is a way to use that same rb_scroll_gallery_shortcode function to render the block in the front end.
I've seen that you can use register_block_type and set the render_callback to rb_scroll_gallery_shortcode, but I need the ID selected in the block to send it to the function in the $atts array
//This uses the shortcode funtion, but doesn't gives the gallery ID
register_block_type( 'cgb/block-rb-scroll-gallery-block', array(
'render_callback' => 'rb_scroll_gallery_shortcode',
) );
You can try to Convert a Shortcode to a Gutenberg Block and after use in your theme,
Registering the Dynamic Block Callback in PHP
/**
* Register the GitHub Gist shortcode
*/
function gggb_init() {
add_shortcode( 'github-gist', 'gggb_render_shortcode' );
register_block_type( 'github-gist-gutenberg-block/github-gist', array(
'render_callback' => 'gggb_render_shortcode',
) );
}
add_action( 'init', 'gggb_init' );
When your block is rendered on the frontend, it will be processed by your render callback:
function gggb_render_shortcode( $atts ) {
if ( empty( $atts['url'] )
|| 'gist.github.com' !== parse_url( $atts['url'], PHP_URL_HOST ) ) {
return '';
}
return sprintf(
'<script src="%s"></script>',
esc_url( rtrim( $atts['url'], '/' ) . '.js' )
);
}
**Note:** this render callback is intentionally different than the Gutenberg block’s edit callback. Our preference is to use GitHub’s provided JavaScript embed code because this lets GitHub change the embed’s behavior at a future date without requiring a developer to make changes.
Refer link for get more information, https://pantheon.io/blog/how-convert-shortcode-gutenberg-block
I've found out the little thing that messed up my code. The problem wasn't that the render_callback() wasn't getting any attributes (though it wasn't), but it was that the editor wasn't saving them because I forgot to remove some testing data from the attribute galleryID
In the registerBlockType:
The save() method should return null.
The attribute should not have a selector data, since it is used to find the value on the markup return by the save(), wich in this case returns null. I've forgot to remove this data, thats why the attribute wasn't being saved.
attributes: {
galleryID: {
type: 'string',
//This data should only be set if the value can be found in the markup return by save().
//Since save() returns null, we let it out
/*source: 'attribute',
/*attribute: 'data-gallery-id',
/*selector: '.rb-scroll-gallery-holder',*/
},
}
I was wondering if any could help on my problem
I have this code from someone that runs fine except that the size does not function, default is always on "thumbnail"
function my_gallery_default_type_set_link( $settings ) {
$settings['galleryDefaults']['link'] = 'file';
$settings['galleryDefaults']['columns'] = '4';
$settings['galleryDefaults']['size'] = 'large';
return $settings;
}
add_filter( 'media_view_settings', 'my_gallery_default_type_set_link');
how can I make this always in large as a default?
This piece of code is actually working, the size of the gallery will be "large" by default if an other size is not manually selected. The real problem come from the dropdown itself that is not correctly set on initialisation, still in WP 4.8.2.
There is a ticket open with more details about this display error.
In the meantime, I found a workaround using the print_media_templates hook :
Step 1 - Define your gallery default image size
function my_gallery_default_settings( $settings ) {
$settings['galleryDefaults']['size'] = 'large';
return $settings;
}
add_filter( 'media_view_settings', 'my_gallery_default_settings');
Step 2 - Debug the dropdown image size default value
function debug_gallery_image_size_default_value() {
?>
<script>
jQuery(document).ready(function(){
wp.media.view.Settings.Gallery = wp.media.view.Settings.Gallery.extend({
template: function(view){
var base_view = wp.media.template('gallery-settings')(view);
var size_option_search = '<option value="'+wp.media.gallery.defaults.size+'">';
var size_option_replace = '<option value="'+wp.media.gallery.defaults.size+'" selected="selected">';
base_view = base_view.replace(size_option_search, size_option_replace);
return base_view;
}
});
});
</script>
<?php
}
add_action('print_media_templates', 'debug_gallery_image_size_default_value');
Why are you using someone else's custom code? There is already a Gallery shortcode with size option in it:
https://codex.wordpress.org/Gallery_Shortcode
Just call it with [gallery size="thumbnail"].
Actually, other code in other answers replaces default settings for existing galleries. Here's the code to apply default settings only to the new gallery:
add_filter( 'media_view_settings', 'theme_gallery_defaults', 10, 2 );
function theme_gallery_defaults( $settings, $post ) {
$defaults = ! empty( $settings['galleryDefaults'] ) && is_array( $settings['galleryDefaults'] ) ? $settings['galleryDefaults'] : array();
$settings['galleryDefaults'] = array_merge( $defaults, array(
'columns' => 5,
'size' => 'large',
'link' => 'file'
) );
return $settings;
}
I need a simple click counter for links in my wordpress posts. I used google a lot but couldnt find a working one. I want to count clicks from a specific class and store it in post_meta or as a custom field to display the count later.
here is some code i found but i cant get it to work..nothting happens when i click the link.
js
jQuery(document).ready(function($) {
$("a[link-out]").click(function() {
var linkout = $(this).attr("link-out");
var data = {
action: 'my_action',
postid: linkout
};
$.post(MyAjax.ajaxurl, data);
});
});
php
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/countclicks.js', array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
function my_action_callback() {
global $wpdb;
$post_id = $_POST['postid'];
$post_id = mysql_real_escape_string($post_id);
$wpdb->query("UPDATE wp_postmeta SET meta_value = meta_value+1 WHERE post_id = '$post_id' AND meta_key = 'clicks_out'");
}
here is another one i found here on stackoverflow, but also doenst work
coding ajax click counter on wordpress
I m using WP pointers in my code...Pointers not display again after i dismiss it once... i deleted my plugin and again activate it but wp pointers not display again... If i install a new wordpress then WP Pointers display but when i dismiss it, then it never comes agains.. Is there a way that when plugin is activated wp pointers appears again...?? Here is my code
function thsp_enqueue_pointer_script_style( $hook_suffix ) {
// Assume pointer shouldn't be shown
$enqueue_pointer_script_style = false;
// Get array list of dismissed pointers for current user and convert it to array
$dismissed_pointers = explode( ',', get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) );
// Check if our pointer is not among dismissed ones
if( !in_array( 'thsp_pointer', $dismissed_pointers ) ) {
$enqueue_pointer_script_style = true;
// Add footer scripts using callback function
add_action( 'admin_print_footer_scripts', 'thsp_pointer_print_scripts' );
}
// Enqueue pointer CSS and JS files, if needed
if( $enqueue_pointer_script_style ) {
wp_enqueue_style( 'wp-pointer' );
wp_enqueue_script( 'wp-pointer' );
}}add_action( 'admin_enqueue_scripts', 'thsp_enqueue_pointer_script_style' );
function thsp_pointer_print_scripts() {
$pointer_content = "<h3>My New Plugin</h3>";
$pointer_content .= "<p>If you ever activated a plugin, then had no idea where its settings page is, raise your hand.</p>";
?>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready( function($) {
$('#toplevel_page_settings').pointer({
content:'<?php echo $pointer_content; ?>',
position:{
edge: 'left', // arrow direction
align: 'center' // vertical alignment
},
pointerWidth: 350,
close:function() {
$.post( ajaxurl, {
pointer: 'thsp_pointer', // pointer ID
action: 'dismiss-wp-pointer'
});
}
}).pointer('open');
});
//]]>
</script>
Dismissed pointers are stored in the wp_usermeta table, for each user, sub meta key dismissed_wp_pointers. Ideally, your plugin should remove the IDs of your pointers for each user on deactivation (see register_deactivation_hook), if you want them to reappear on reactivation.