I have two forms in my website. Both were working fine. but suddenly now they are not working. Emails are not going from both the forms.
// This function gets called when user clicks on submit button
<script type="text/javascript">
var $ = jQuery;
function sendMessage(){
var name = $('[name="name"]').val();
var email = $('[name="email"]').val();
var phone = $('[name="phone"]').val();
var message = $('[name="message"]').val();
var filter = /^[7-9][0-9]{9}$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(name == '')
{
$('.name-error').show();
}
else
{
$('.name-error').hide();
}
if(email == '')
{
$('.email-error').show();
}
else
{
$('.email-error').hide();
}
if(phone == '')
{
$('.phone-error').show();
}
else
{
$('.phone-error').hide();
}
if(message == '')
{
$('.message-error').show();
}
else
{
$('.message-error').hide();
}
if(name != '' && email != '' && phone != '' && message != ''){
if(emailReg.test(email)){
if(filter.test(phone)){
var data = {
url: '<?php echo admin_url('admin-ajax.php');?>',
type: 'POST',
action: 'send_mails',
formdata: $("#contact").serialize()
};
var myRequest = jQuery.post(data.url, data, function(response){
console.log(response)
});
myRequest.done(function(){
$('#msg').html("<p class='msg' style='background-color:#dff0d8; border-color: #d6e9c6; color:#3c763d; padding:10px; border-radius:4px;'>The Email has been sent successfully!</p>").fadeIn('slow');
$('#msg').delay(5000).fadeOut('slow');
});
$("#contact").trigger("reset");
$('#msg').html("<p class='msg' style='background-color:#dff0d8; border-color: #d6e9c6; color:#3c763d; padding:10px; border-radius:4px;'>The Email has been sent successfully!</p>").fadeIn('slow');
$('#msg').delay(5000).fadeOut('slow');
}
else
{
alert("Provide valid mobile number");
}
}
else
{
alert("Provide valid Email Id");
}
}
else
{
// alert("Kindly enter all the details");
return false;
}
}
</script>
This is function from functions.php file.
function send_mails()
{
$formData = $_POST['formdata'];
$data = array();
parse_str($formData, $data);
$name = $data['name'];
$email = $data['email'];
$phone = $data['phone'];
$message = $data['message'];
$msg = "A new enquiry has been posted on the website\n";
$msg.= "Name: ".$name."\n";
$msg.= "Email: ".$email."\n";
$msg.= "Phone: ".$phone."\n";
$msg.= "Message: ".$message."\n";
$headers = array('Content-Type: text/html; charset=UTF-8');
//echo $msg;
$admin_email = get_option( 'admin_email' );
// print_r($admin_email);
$res = wp_mail('email',"Enquiry",$msg,$headers);
if($res)
{
echo "Mail has been sent";
}
else
{
echo "Could not send mail";
debug_wpmail($res);
}
die();
}
add_action('wp_ajax_send_mails', 'send_mails');
add_action('wp_ajax_nopriv_send_mails', 'send_mails');
debug_wpmail returns the error "Could not instantiate mail function". I did not find anything on google.
if ( ! function_exists('debug_wpmail') ) :
function debug_wpmail( $result = false ) {
if ( $result )
return;
global $ts_mail_errors, $phpmailer;
if ( ! isset($ts_mail_errors) )
$ts_mail_errors = array();
if ( isset($phpmailer) )
$ts_mail_errors[] = $phpmailer->ErrorInfo;
print_r('<pre>');
print_r($ts_mail_errors);
print_r('</pre>');
}
endif;
Can you modify this part :
From
$res = wp_mail('email',"Enquiry",$msg,$headers);
To
$res = wp_mail($admin_email,'Enquiry',$msg,$headers);
This happens due to your site haven't been configured with email service provider like Google/SendGrid or SMTP Or It just goes removed. Example configuration can be found below:
Related
In wpDataTables, I would like to modify (i.e. conditionally format) each cell value in a specific column for a specific table programmatically using PHP. How would I accomplish this?
First, install the Code Snippets plugin. Then create a new snippet set to "Run Snippet Everywhere" (required for JSON filtering) using the code below. It will filter both HTML and JSON. For more information, refer to wpDataTables - Filters.
function custom_wpdatatables_filter_initial_table_construct($tbl) {
// Edit below.
$table_name_to_modify = 'My Table Name';
$table_column_to_modify = 'my_table_column';
$cell_modification_function = function($value) {
return 'Modified: ' . $value;
};
// Check table name.
if ($tbl->getName() !== $table_name_to_modify) {
return $tbl;
}
$rows = $tbl->getDataRows();
foreach ($rows as &$row) {
if (array_key_exists($table_column_to_modify, $row)) {
$row['intermentobituary'] = $cell_modification_function($row['intermentobituary']);
}
}
$tbl->setDataRows($rows);
return $tbl;
}
add_filter('wpdatatables_filter_initial_table_construct', 'custom_wpdatatables_filter_initial_table_construct', 10, 1);
function custom_wpdatatables_filter_server_side_data($json, $tableId, $get) {
// Edit below.
$table_name_to_modify = 'My Table Name';
$table_column_to_modify = 'my_table_column';
$cell_modification_function = function($value) {
return 'Modified: ' . $value;
};
// Check table name.
$tableData = WDTConfigController::loadTableFromDB($tableId);
if (empty($tableData->content)) {
return $json;
} else if ($tableData->title !== $table_name_to_modify) {
return $json;
}
// Get columns.
$columns = [];
foreach ($tableData->columns as $column) {
// wdt_ID will be first column.
$columns[] = $column->orig_header;
}
// Modify column values.
$json = json_decode($json, true);
$rows = $json['data'];
foreach ($rows as $row_key => $row_value) {
foreach ($row_value as $row_attr_key => $row_attr_value) {
if ( ! empty($columns[$row_attr_key]) && $columns[$row_attr_key] === $table_column_to_modify) {
$rows[$row_key][$row_attr_key] = $cell_modification_function($row_attr_value);
}
}
}
$json['data'] = $rows;
return json_encode($json);
}
add_filter('wpdatatables_filter_server_side_data', 'custom_wpdatatables_filter_server_side_data', 10, 3);
I have a CF7-Form that asks for a name and date of birth.
The name is not a required field, but if a name is entered, the birthday is required in any case.
Therefore, the date of birth is not included as required by default.
CF7 Simplified code:
<div class="cf7-conditional-wrapper">
<label>Name [text your-name class:field-a]</label>
<label>Birthday<span class="asterisk-placeholder"></span> [date your-date class:field-b-required-if-a-set]</label>
</div>
In the first step I work on the fact that the field should also be perceived as a required field by CF7.
let cf7_conditional_wrappers = document.getElementsByClassName("cf7-conditional-wrapper");
for (let cf7_conditional_wrapper of cf7_conditional_wrappers) {
let field_a = cf7_conditional_wrapper.getElementsByClassName("field-a")[0],
field_b = cf7_conditional_wrapper.getElementsByClassName("field-b-required-if-a-set")[0],
asterisk_placeholder = cf7_conditional_wrapper.getElementsByClassName("asterisk-placeholder")[0];
if (field_a && field_b && asterisk_placeholder) {
checkRequiredFields(field_a, field_b, asterisk_placeholder);
}
}
function checkRequiredFields(field_a, field_b, asterisk_placeholder) {
let timeout = null;
// Listen for keystroke events
field_a.addEventListener('keyup', function (e) {
clearTimeout(timeout);
timeout = setTimeout(function () {
//console.log('Input Value:', field_a.value);
//console.log('Input Value Length:', field_a.value.length);
if (field_a.value.length > 0) {
// Set Required
field_b.classList.add('wpcf7-validates-as-required');
//field_b.classList.add('wpcf7-not-valid');
field_b.setAttribute("aria-required", "true");
//field_b.setAttribute("aria-invalid", "false");
//field_b.setAttribute("required", "");
//field_b.required = true;
asterisk_placeholder.textContent = "*";
} else {
field_b.classList.remove('wpcf7-validates-as-required');
//field_b.classList.remove('wpcf7-not-valid');
field_b.removeAttribute("aria-required");
//field_b.setAttribute("aria-invalid", "false");
//field_b.removeAttribute("required");
//field_b.required = false;
asterisk_placeholder.textContent = "";
}
}, 1000);
});
}
Everything appears visually to be correct, but the new required field is not checked when the form is submitted.
Does anyone have any tips that I haven't considered?
For safety, I would also solve the same query on the server side via PHP and have looked at the following approach. However, the entry from 2015 was unsuccessful in the first tests, although the code is still similar to that of the plugin's database today.
add_filter( 'wpcf7_validate_date', 'custom_date_confirmation_validation_filter', 20, 2 );
function custom_date_confirmation_validation_filter( $result, $tag ) {
if ( 'birth-date' == $tag->name ) {
$your_birth_date = isset( $_POST['birth-date'] ) ? trim( $_POST['birth-date'] ) : '';
if ( $your_birth_date != '' ) {
$result->invalidate( $tag, "Test to override Required Message" );
}
}
return $result;
}
Example in manual from 2015: https://contactform7.com/2015/03/28/custom-validation/
add_filter( 'wpcf7_validate_date', 'custom_date_confirmation_validation_filter', 20, 2 );
function custom_date_confirmation_validation_filter( $result, $tag ) {
$name = isset( $_POST['name'] ) ? trim( $_POST['name'] ) : '';
if ( 'birth-date' == $tag->name ) {
$your_birth_date = isset( $_POST['birth-date'] ) ? trim( $_POST['birth-date'] ) : '';
if ( trim($name) != '' && trim($your_birth_date) == '' ) {
$result->invalidate( $tag, "Please enter date of birth" );
}
}
return $result;
}
Check if name is not empty and birth date is empty then show warning message.
I have problem with my telegram bot.I want to make Keybaord for my bot. When I run my telegram api url from my browser it works:
https://api.telegram.org/mybottoken/sendmessage?chat_id=93119306&text=something&reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]], "one_time_keyboard":true};
but
When I want run to this url($sendto Variable) in my php file this not work.
my php code is:
<?php
define('BOT_TOKEN', '183690241:AAHgluc7D9g0DF_InurfBj2YdBgPE7fmymo');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
$array = array();
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$chatText = $update["message"]["text"];
// compose reply
$reply = sendMessage();
// send reply
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply."&reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]], "one_time_keyboard":true};
file_get_contents($sendto);
function sendMessage(){
global $chatID;
global $chatText;
if ($chatText =="/start") {
$message = "Salam - Roboate Megat Hastam";
}
elseif ($chatText =="Khoobi?") {
$message = "Merc - Shomaa khobi?";
}
elseif ($chatText =="Chand salete?") {
$message = "Be Tu Che!";
}
else
{
$message = "No Command";
}
return rawurlencode($message);
}
?>
please help where i made mistake.
thanks all guys.
Try this code:
var_dump($keyboard = json_encode($keyboard = [
'keyboard' => [
['Yes'],['No'],['Maybe'],
['1'],['2'],['3'],
] ,
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
]),true);
function sendKeyboard($chat_id, $keyboard) {
$text = "Merc - Shomaa khobi?";
file_get_contents(API_URL ."sendMessage?chat_id=".$chat_id."&reply_markup=".$keyboard."&text=".urlencode($text));
}
if($message == "/start"){
sendKeyboard($chat_id, $keyboard);
}
I am trying to upload video/image to facebook albumb using php sdk 4 asynchronously.I googled and found that php asynchronous call be sent using fsockopen. However, it is not working for facebook request. I have two files, one for checking login and getting token. Then second file is called for uploading the file to facebook. Below is the code for first file:
// start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// init app with app id and secret
FacebookSession::setDefaultApplication('xxxxx', 'yyyy');
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://website.com/user/login/page/view/fb-share-php1' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
}catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb'] = $session;
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
//$session = new FacebookSession( $session->getToken() );
// graph api request for user data
//$request = new FacebookRequest( $session, 'GET', '/me' );
//$response = $request->execute();
backgroundPost('http://website.com/user/login/page/view/fb-share-php');
// get response
//$graphObject = $response->getGraphObject()->asArray();
// print profile data
//echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
}else {
// show login url
echo 'Login';
}
function backgroundPost($url){
$parts=parse_url($url);
//print_r($parts);exit;
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
echo "test";
return false;
} else {
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ". 0 ."\r\n";
$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
// print_r($out);exit;
fwrite($fp, $out);
fclose($fp);
return true;
}
}
And second file is:
// start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
$session = $_SESSION['fb'] ;
file_put_contents('file.txt', serialize($session));
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'source' => '#/var/www/website-root/images/add_more.png',
'message' => 'User provided message'
)
))->execute()->getGraphObject();
file_put_contents('files.txt', serialize($session));
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
Finally, I figured out the way to achieve it. Now, I am using facebook javascript sdk with php sdk. Following is the process:
1)Get access token from javascript sdk(first file) and pass it to background along with the url of image/video. Code may be modified, if image/video is being uploaded through source.
2) php file(2nd file) containing function for executing backend-process(which is in third file) receives the posted data and and call the third file(in the form of url) and pass the data to it as well.
3) File(s) are uploaded to facebook through php sdk 4(third file)
Below is the code for first file containing javascript sdk code:
<script>
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function() {
FB.init({
appId : 'your app id',
xfbml : true,
version : 'v2.0'
});
FB.login(function(response){
console.log(response);
if (response.status === 'connected') {
var data = new Array();
alert('Logged into your app and Facebook.');
//type: 0 for photo and type:1 for video. Create data array dynamically for real word applications
data[0]= {url: 'http://url-of-video-file.mov',privacy : 'SELF', message: "title of video", type:1};
data[1]= {url: 'http://url-to-image-file.png',privacy : 'SELF', message: "photo caption", type:0};
$.ajax({
url: 'http://url-of-second-file/containing-code-for/backend-process',
data: {data: data, accessToken:response.authResponse.accessToken},
type: 'POST',
success:function(){
alert("photo uploaded");
}
});
},{scope:'email'});
}
</script>
Now code of second file which receives data and execute back-end process:
<?php
//session_start();
ignore_user_abort(true);
set_time_limit(0);
function backgroundPost($url){
$parts=parse_url($url);
//print_r($parts);exit;
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
echo "test";
return false;
} else {
$vars = $_POST;
$content = http_build_query($vars);
//file_put_contents('url.txt',$content);exit;
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ". strlen($content) ."\r\n";
//$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
// print_r($out);exit;
fwrite($fp, $out);
fwrite($fp,$content);
fclose($fp);
return true;
}
}
backgroundPost('http://link-to-third-file/containing-code-for-facebook-upload');
Now code of third file, which will actually upload the files. Please note, video files need to be downloaded before it can be uploaded.
<?php
// start session
//session_start();
error_reporting(1);
ignore_user_abort(true);
set_time_limit(0);
#ini_set('display_errors', 1);
//include facebook library through autoload
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// init app with app id and secret
FacebookSession::setDefaultApplication('app_id','secret_key' );
$session = new FacebookSession( $_POST['accessToken'] );
foreach($_POST['data'] as $key => $data){
if($data['type'] == 1){
$ext = substr($data['url'],strrpos($data['url'],'.'));
$file = '/path/to/temp/location/for/saving/video/'.time().$ext;
if(file_put_contents($file,file_get_contents($data['url']))){
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => '#'.$file,
'title' => $data['message'],
'privacy' => json_encode(array('value' => $data['privacy'])),
'published' => true
)
))->execute()->getGraphObject()->asArray();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}else{
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'url' => $data['url'],
'message' => $data['message'],
'privacy' => json_encode(array('value' => $data['privacy'])),
'published' => true
)
))->execute()->getGraphObject()->asArray();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}
?>
I want to improve the process of uploading pictures in a Real Estate Website. This website is running WordPress 3.8. The theme offers front end submission with a very simple interface. The user selects the images (one by one) and then clicks to add. Finally when the user submit the listing all the images are uploaded at once. This is the screenshot of how it looks: Original Option: Listing Images.
This is the JQuery Plugin I am currently using,
/*!
* jQuery imagesLoaded plugin v2.1.1
* http://github.com/desandro/imagesloaded
*
* MIT License. by Paul Irish et al.
*/
/*jshint curly: true, eqeqeq: true, noempty: true, strict: true, undef: true, browser: true */
/*global jQuery: false */
;(function($, undefined) {
'use strict';
// blank image data-uri bypasses webkit log warning (thx doug jones)
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
$.fn.imagesLoaded = function( callback ) {
var $this = this,
deferred = $.isFunction($.Deferred) ? $.Deferred() : 0,
hasNotify = $.isFunction(deferred.notify),
$images = $this.find('img').add( $this.filter('img') ),
loaded = [],
proper = [],
broken = [];
// Register deferred callbacks
if ($.isPlainObject(callback)) {
$.each(callback, function (key, value) {
if (key === 'callback') {
callback = value;
} else if (deferred) {
deferred[key](value);
}
});
}
function doneLoading() {
var $proper = $(proper),
$broken = $(broken);
if ( deferred ) {
if ( broken.length ) {
deferred.reject( $images, $proper, $broken );
} else {
deferred.resolve( $images );
}
}
if ( $.isFunction( callback ) ) {
callback.call( $this, $images, $proper, $broken );
}
}
function imgLoadedHandler( event ) {
imgLoaded( event.target, event.type === 'error' );
}
function imgLoaded( img, isBroken ) {
// don't proceed if BLANK image, or image is already loaded
if ( img.src === BLANK || $.inArray( img, loaded ) !== -1 ) {
return;
}
// store element in loaded images array
loaded.push( img );
// keep track of broken and properly loaded images
if ( isBroken ) {
broken.push( img );
} else {
proper.push( img );
}
// cache image and its state for future calls
$.data( img, 'imagesLoaded', { isBroken: isBroken, src: img.src } );
// trigger deferred progress method if present
if ( hasNotify ) {
deferred.notifyWith( $(img), [ isBroken, $images, $(proper), $(broken) ] );
}
// call doneLoading and clean listeners if all images are loaded
if ( $images.length === loaded.length ) {
setTimeout( doneLoading );
$images.unbind( '.imagesLoaded', imgLoadedHandler );
}
}
// if no images, trigger immediately
if ( !$images.length ) {
doneLoading();
} else {
$images.bind( 'load.imagesLoaded error.imagesLoaded', imgLoadedHandler )
.each( function( i, el ) {
var src = el.src;
// find out if this image has been already checked for status
// if it was, and src has not changed, call imgLoaded on it
var cached = $.data( el, 'imagesLoaded' );
if ( cached && cached.src === src ) {
imgLoaded( el, cached.isBroken );
return;
}
// if complete is true and browser supports natural sizes, try
// to check for image status manually
if ( el.complete && el.naturalWidth !== undefined ) {
imgLoaded( el, el.naturalWidth === 0 || el.naturalHeight === 0 );
return;
}
// cached images don't fire load sometimes, so we reset src, but only when
// dealing with IE, or image is complete (loaded) and failed manual check
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
if ( el.readyState || el.complete ) {
el.src = BLANK;
el.src = src;
}
});
}
return deferred ? deferred.promise( $this ) : $this;
};
})(jQuery);
My goal is to have a more flexible system, where all the images can be selected at the same time and it starts loading right away. This will speed up the process and improve user experience. Also to arrange them in any order by moving them around. This is an example I found on another website. See screenshot: New Option: Multiple Image Upload
What programing language is good for this development? Any recommendations of where I can find code snippets for this application? Thanks in advance for your help!!
rough draft.....you need jquery and wordpress media js..just watch the js variable names below if there are errors it will be with these...
php in functions file:
if(function_exists( 'wp_enqueue_media' )){
wp_enqueue_media();
}
javascript...add to the page header..wp_enqueue_scripts or to your template (do this first to make sure its working!) you'll need your element called upload_image_button or change accordinely
// Uploading files
var media_uploader;
jQuery('.upload_image_button').live('click', function( event ){
var button = jQuery( this );
// If the media uploader already exists, reopen it.
if ( media_uploader ) {
media_uploader.open();
return;
}
// Create the media uploader.
media_uploader = wp.media.frames.media_uploader = wp.media({
title: button.data( 'uploader-title' ),
// Tell the modal to show only images.
library: {
type: 'image',
query: false
},
button: {
text: button.data( 'uploader-button-text' ),
},
multiple: button.data( 'uploader-allow-multiple' )
});
// Create a callback when the uploader is called
media_uploader.on( 'select', function() {
var selection = media_uploader.state().get('selection'),
input_name = button.data( 'input-name' ),
bucket = $( '#' + input_name + '-thumbnails');
selection.map( function( attachment ) {
attachment = attachment.toJSON();
// console.log(attachment);
bucket.append(function() {
return '<img src="'+attachment.sizes.thumbnail.url+'" width="'+attachment.sizes.thumbnail.width+'" height="'+attachment.sizes.thumbnail.height+'" class="submission_thumb thumbnail" /><input name="'+input_name+'[]" type="hidden" value="'+attachment.id+'" />'
});
});
});
// Open the uploader
media_uploader.open();
});
template file:
<span class="upload_image_button alt_button" data-input-name="images" data-uploader- title="Upload Images" data-uploader-button-text="Add to Submission" data-uploader-allow-multiple="true">Upload</span>
php $_POST return
if ( !empty( $_POST['submission_images'] ) ) {
// do something with the files, set featured img, add to content or save post_meta
}
or..............i came across a plugin that does this a lot better........sorry its in OOP and designed on back end but you can modify for front end! The problem with multi file uploader from WP is it required users to hit "CTRL" + click with no guidance....massive problem on front-end forms...this one you can add more guidance to easily...sorry i havent a frontend sample yet, i have yet to create :)
"Multi File Upload"
e.g.
public function render_meta_box_content($post)
{
// Add an nonce field so we can check for it later.
wp_nonce_field('miu_inner_custom_box', 'miu_inner_custom_box_nonce');
// Use get_post_meta to retrieve an existing value from the database.
$value = get_post_meta($post->ID, '_ad_images', true);
$metabox_content = '<div id="miu_images"></div><input type="button" onClick="addRow()" value="Add Image" class="button" />';
echo $metabox_content;
$images = unserialize($value);
$script = "<script>
itemsCount= 0;";
if (!empty($images))
{
foreach ($images as $image)
{
$script.="addRow('{$image}');";
}
}
$script .="</script>";
echo $script;
}
save function
public function save_image($post_id)
{
/*
* We need to verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times.
*/
// Check if our nonce is set.
if (!isset($_POST['miu_inner_custom_box_nonce']))
return $post_id;
$nonce = $_POST['miu_inner_custom_box_nonce'];
// Verify that the nonce is valid.
if (!wp_verify_nonce($nonce, 'miu_inner_custom_box'))
return $post_id;
// If this is an autosave, our form has not been submitted,
// so we don't want to do anything.
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
// Check the user's permissions.
if ('page' == $_POST['post_type'])
{
if (!current_user_can('edit_page', $post_id))
return $post_id;
} else
{
if (!current_user_can('edit_post', $post_id))
return $post_id;
}
/* OK, its safe for us to save the data now. */
// Validate user input.
$posted_images = $_POST['miu_images'];
$miu_images = array();
foreach ($posted_images as $image_url)
{
if(!empty ($image_url))
$miu_images[] = esc_url_raw($image_url);
}
// Update the miu_images meta field.
update_post_meta($post_id, '_ad_images', serialize($miu_images));
}
js file
jQuery(document).ready(function(){
jQuery('.miu-remove').live( "click", function(e) {
e.preventDefault();
var id = jQuery(this).attr("id")
var btn = id.split("-");
var img_id = btn[1];
jQuery("#row-"+img_id ).remove();
});
var formfield;
var img_id;
jQuery('.Image_button').live( "click", function(e) {
e.preventDefault();
var id = jQuery(this).attr("id")
var btn = id.split("-");
img_id = btn[1];
jQuery('html').addClass('Image');
formfield = jQuery('#img-'+img_id).attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html){
if (formfield) {
fileurl = jQuery('img',html).attr('src');
jQuery('#img-'+img_id).val(fileurl);
tb_remove();
jQuery('html').removeClass('Image');
} else {
window.original_send_to_editor(html);
}
};
});
function addRow(image_url){
if(typeof(image_url)==='undefined') image_url = "";
itemsCount+=1;
var emptyRowTemplate = '<div id=row-'+itemsCount+'> <input style=\'width:70%\' id=img- '+itemsCount+' type=\'text\' name=\'miu_images['+itemsCount+']\' value=\''+image_url+'\' />'
+'<input type=\'button\' href=\'#\' class=\'Image_button button\' id=\'Image_button- '+itemsCount+'\' value=\'Upload\'>'
+'<input class="miu-remove button" type=\'button\' value=\'Remove\' id=\'remove-'+itemsCount+'\' /></div>';
jQuery('#miu_images').append(emptyRowTemplate);
}