So I want my users to be able to create a post in the frontend and upload an image with a form I've created.
When the image is uploaded I want to update an ACF-field with the uploaded image.
I've seen some posts on this but none of them are explained any good.
I want to use Ajax and I want to use axios, so please no jQuery. I also use Qs.
The image itself is never uploaded but the file name is inserted in the media library.
Thank you!
HTML
<form enctype="multipart/form-data" method="post" id="register-store-form">
<fieldset class="store-images mb-3">
<label for="store-images">Add images</label>
<input type="file" id="store_images" name="store_images" accept="image/png, image/jpeg">
</fieldset>
<button class="btn btn-primary" id="update-store">Save store</button>
</form>
JS
const Qs = require('qs');
const axios = require('axios');
const saveStoreBtn = document.querySelector('#update-store');
const addStore = document.querySelector('#add-one-more-store');
function saveStore(e) {
const storeName = document.querySelector('#store-name');
const storeImages = document.querySelector('#store_images');
const storeImageFile = storeImages.files[0];
const ajaxData = {
action : 'create_store',
security : shkGlobal.addStore,
name : storeName.value,
image_name : storeImageFile.name,
image_type : storeImageFile.type,
description : storeDescription.value
};
axios.post(shkGlobal.adminUrl, Qs.stringify(ajaxData))
.then(function(response) {
saveStoreBtn.innerHTML = "Thank you";
})
.catch(err => console.log('Not working', err));
};
updateStoreBtn.addEventListener('click', saveStore);
PHP
function create_store() {
check_ajax_referer('add_store', 'security');
$name_value = $_POST['name'];
$image_name = $_POST['image_name'];
$image_type = $_POST['image_type'];
$post_data = array(
'post_type' => 'store',
'post_title' => htmlentities($name_value),
'post_content' => $_POST['description'],
'post_status' => 'draft'
);
$post_id = wp_insert_post( $post_data );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES[$image_name];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ($movefile) {
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'].'/'.$image_name,
'post_mime_type' => $image_type,
'post_title' => $image_name,
'post_content' => 'File '.$image_name,
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $movefile['file']);
update_field('field_602019eba7767', $attach_id, $post_id);
}
echo json_decode($response);
exit;
}
add_action('wp_ajax_create_store', 'create_store');
add_action('wp_ajax_nopriv_create_store', 'create_store');
There are two problems in your case, first one that you are uploading multiple files, so structure of $_FILES will be different. Second one is that you specified store_images instead store_images[] for multiple file upload.
So in html change <input type="file" name="store_images" multiple> to <input type="file" name="store_images[]" multiple>
And in php, change your code accordingly to example below.
$files = $_FILES['store_images];
foreach ($files as $key => $value) {
if ($files['name']) {
$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);
}
}
}
Related
I have code to get some data (terms = page-a) built with Wordpress.
Currently, the data of page-a is acquired like'terms' =>'page-a' and displayed on the example.com/page-a page.
I would like to change this data acquisition code so that the data along the lower page url can be acquired (for example, the data on page-b at example.com/page-b).
I created a code to get the url with $_SERVER and convert it, but I can't get the url because I am using ajax. I want to get the url with javascript and pass it to php.
How should I make the changes?
functions.php
add_action('wp_ajax_get_case', 'dk_get_case');
add_action('wp_ajax_nopriv_get_case', 'dk_get_case');
function dk_get_case() {
$headers['Access-Control-Allow-Origin'] = '*';
$return = ['status' => false, 'data' => [], 'message' => ''];
$case_clinics = [1,2,3,4];
foreach($case_clinics as $key => $case_clinic){
// (1)Get the current URL
$http = is_ssl() ? 'https' : 'http' . '://';
$url = $http . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
// (2)Get a string such as'page-a' from the URL
$keys = parse_url($url);
$path = explode("/", $keys['path']);
$terms = $path[2];
$dk_posts = get_posts(
array(
'showposts' => -1,
'post_type' => 'case',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'case_clinic',
'field' => 'term_id',
'terms' => $case_clinic
),
array(
'taxonomy' => 'case_category',
'field' => 'slug',
'terms' => 'page-a'
)
)
)
);
taxonomy-case_category-page-a.php
<div class="col case-right">
<h3 style="font-family:'Futura PT'; font-weight:600">Clinic</h3>
<h4 style="font-weight:600">Clinic</h4>
//data display position
<div class="case-img" data-slider-3></div>
<div class="popup"></div>
</div>
Tried
footer.php
<script>
jQuery(document).ready(function () {
var url = window.location.href;
$.ajax({
type: "GET",
url: "taxonomy-case_category-page-a.php",
data: {"url": url},
});
});
taxonomy-case_category-page-a.php
<?php var_dump($_GET['url']); ?>
error
GET: 404error
https://example.com/pagea/taxonomy-case_category-page-a.php?url=https%3A%2F%2Fcharme-beauty.jp%2Fstaging%2Fcase%2Fpagea%2F
I am using ajax to send data to a custom rest endpoint. I am doing this because i'm creating a filter function on my WP site.
Now I am stuck trying to get the tax_query to work with my array of terms collected with JS on the front end. No matter what I do I cant seem to get this to work, and I am strongly suspecting this is only a minor error that I keep overlooking...
Just to clarify, the ajax sends the request successfully but the query returns all posts no matter what.
Here is the checkboxes used on the front end:
<div class="form-group">
<?php
if( $terms = get_terms( array( 'taxonomy' => 'utst', 'hide_empty' => false, 'orderby' => 'name' ) ) ) :
foreach ( $terms as $term ) :
echo '<div class="form-check">';
echo '<label class="form-check-label" for="'.$term->slug.'"><input class="form-check-input" type="checkbox" id="'.$term->slug.'" name="utstyrAr[]" value="'.$term->term_id.'"> '.$term->name.'</label>'; // ID of the category as the value of an option
echo '</div>';
endforeach;
endif;
?>
</div>
The JS (ajax function):
filterOppdrag(fiOppdrag) {
var utst = [];
var utstyrArray = document.getElementsByName("utstyrAr[]");
for (var i = 0; i < utstyrArray.length; i++) {
if(utstyrArray[i].type =='checkbox' && utstyrArray[i].checked == true) utst.push(utstyrArray[i].value);
}
console.log(utst);
$.ajax({
url: the.root + '/wp-json/myfilter/v1/filter',
type: 'GET',
data: {
'checkUtst' : utst,
},
success: (response) => {
console.log(response);
},
error: (response) => {
console.log(response);
}
});
}
And the wp_query (php):
function myFilter ($data) {
$checkUtst = sanitize_text_field($data['checkUtst']);
//Main $args
$args = array(
'post_type' => 'ml_opp', // Query only "ml_opp" custom posts
'post_status' => 'publish', // Query only posts with publish status
'orderby' => 'date', // Sort posts by date
'order' => 'ASC' // ASC or DESC
);
// for taxonomies / utstyr
if( isset( $utstyr ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'ml_utst',
'field' => 'id',
'terms' => $checkUtst
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
This returns all the posts regardless of terms no matter what I pass through. I get no error messages and yes I have tested so that there is value in the array when I send it to the query. But what happens to it on the road there, I dont know. That's why i figure that Its probably just a rookie mistake I am making here.
Any help would be greatly appreciated!
Have you tried removing the wrapping array and not using a key?
$args = array(
'taxonomy' => 'ml_utst',
'field' => 'id',
'terms' => $checkUtst
);
I have a Wordpress website that users can submit posts from the front-end. Im trying to integrate dropzone.js so users can submit images via drag and drop and sort images from featured image and gallery images kinda like what craigslist has.
My question is how do I get the featured image to get added to a file input
<input id="fileUpload" type="file" name="feat-img" accept="image/*" value="">
and the gallery image get added to
<input id="gallery-photo-add" type="file" name="muti_files[]" accept="image/*" multiple>
Heres my code
Html
<div class="dropzone" drop-zone="" id="file-dropzone"></div>
<ul class="visualizacao sortable dropzone-previews" style="border:1px solid #000"></ul>
<div class="preview" style="display:none;">
<li>
<div class="dz-preview dz-file-preview">
<img data-dz-thumbnail />
<input id="fileUpload" type="file" name="feat-img" accept="image/*" value="">
<input id="gallery-photo-add" type="file" name="muti_files[]" accept="image/*" multiple>
</div>
</li>
</div>
Javascript
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>
<script type="text/javascript">
var $ = jQuery
$(document).ready(function(){
$('.sortable').sortable();
});
$.getScript('https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/min/dropzone.min.js',function(){
$('#file-dropzone').dropzone({
url: "/",
maxFilesize: 100,
paramName: "uploadfile",
maxThumbnailFilesize: 99999,
previewsContainer: '.visualizacao',
previewTemplate : $('.preview').html(),
init: function() {
this.on('completemultiple', function(file, json) {
$('.sortable').sortable('enable');
});
this.on('success', function(file, json) {
alert('aa');
});
this.on('addedfile', function(file) {
console.log('File1',file);
});
this.on('drop', function(file) {
console.log('File2',file);
});
}
});
});
$(document).ready(function() {});
</script>
PHP
if( ! empty( $_FILES ) ){
$featured_image = $_FILES['feat-img'];
$attachment_id = upload_user_file( $featured_image, $post_id);
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$filee = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $filee);
foreach ($_FILES as $filee => $array) {
$newupload = my_handle_attachment($filee, $post_id);
}
}
}
}
if ( ! empty( $_FILES['muti_files'] ) ) {
$files = $_FILES['muti_files'];
foreach ($files['name'] 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]
);
}
$_FILES = array("muti_files" => $file);
$i=1;
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attachment_id = media_handle_upload($file, $post_id);
$vv .= $attachment_id . ",";
$i++;
}
update_post_meta($post_id, '_product_image_gallery', $vv);
}
}
All this works fine if i dont use dropzone.js and just the <input type="file"> here is a codepen so you can see what im trying to do https://codepen.io/T-SEA/pen/OdqQOw
Campaign Monitor seems to have updated their code snippets to use a different method of submitting the forms. Now in the <form> tag there's a data-id attribute. None of the usual ways of submitting the forms using Ajax work anymore. Does anybody know how to use Ajax to submit the new style of Campaign Monitor forms?
Here's the code snippet Campaign Monitor gives me:
<form id="subForm" class="js-cm-form" action="https://www.createsend.com/t/subscribeerror?description=" method="post" data-id="A61C50BDC994654B1D79D5719EC1255C09788D1CED7F46D508DAE8944C2CB34BA5EC78954EB81FB5F54AD0716B1F245E696D5CFAF72B819D19DC3B44517">
<p>
<label for="fieldEmail">Email</label>
<br />
<input id="fieldEmail" name="cm-wmpt-wmpt" type="email" class="js-cm-email-input"
required />
</p>
<p>
<button class="js-cm-submit-button" type="submit">Subscribe</button>
</p>
</form>
<script type="text/javascript" src="https://js.createsend1.com/javascript/copypastesubscribeformlogic.js"></script>
I emailed their support, so I can answer the question myself. They've replaced all the old methods with their API. You need to have the form's action set to your own endpoint (e.g. signup.php).
I'm using PHP, so I downloaded their PHP API wrapper from https://github.com/campaignmonitor/createsend-php. A simple example is like this:
require_once 'lib/campaignmonitor/csrest_subscribers.php';
$auth = array(
'api_key' => 'Your API key'
);
$wrap = new CS_REST_Subscribers( 'Your list ID', $auth );
$result = $wrap->add( array(
'EmailAddress' => 'Subscriber email',
'Name' => 'Subscriber name',
'CustomFields' => array(
array(
'Key' => 'Field 1 Key',
'Value' => 'Field Value'
),
array(
'Key' => 'Field 2 Key',
'Value' => 'Field Value'
),
array(
'Key' => 'Multi Option Field 1',
'Value' => 'Option 1'
),
array(
'Key' => 'Multi Option Field 1',
'Value' => 'Option 2'
)
),
'ConsentToTrack' => 'yes',
'Resubscribe' => true
) );
Update: Here's my complete PHP if you're curious:
require_once 'libs/campaignmonitor/csrest_subscribers.php';
$success_message = 'You\'ve been signed up for our email list.';
$error_message_general = 'There was a problem signing you up for the email list. Please try again.';
$error_message_format = 'Please enter a valid email address.';
if ( $_SERVER[ 'REQUEST_METHOD' ] !== 'POST' ) {
renderResponse( true, $error_message_general );
}
else {
$api_key = 'your_api_key_here';
$list_id = 'your_list_id_here';
$email = array_key_exists( 'email', $_POST ) ? $_POST[ 'email' ] : '';
$email = cleanInput( $email );
if ( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
try {
$auth = array(
'api_key' => $api_key
);
$wrap = new CS_REST_Subscribers( $list_id, $auth );
$result = $wrap->add( array(
'EmailAddress' => $email,
'ConsentToTrack' => 'yes',
'Resubscribe' => true
) );
if ( $result->was_successful() )
renderResponse( false, $success_message );
else
renderResponse( true, $error_message_general );
}
catch ( Exception $e ) {
renderResponse( true, $error_message_general );
}
}
else {
renderResponse( true, $error_message_format );
}
}
function renderResponse( $error, $message ) {
header( 'Content-Type: application/json' );
$result = [
'error' => $error,
'message' => $message
];
echo json_encode( $result );
die();
}
function cleanInput( $data ) {
$data = trim( $data );
$data = stripslashes( $data );
$data = htmlspecialchars( $data );
return $data;
}
I have a file in my server folder and now I want to download that file on page load.
Example :
If I click on Our products than a file has been downloaded automatically in users system from my server.
// in controller
public function download() {
$this->viewClass = 'Media';
// Render app/webroot/files/example.docx
$params = array(
'id' => 'example.docx', // file name
'name' => 'example',
'extension' => 'docx', // its file extension name
'mimeType' => array(
'docx' => 'application/vnd.openxmlformats-officedocument' .
'.wordprocessingml.document'
),
'path' => 'files' . DS
);
$this->set($params);
}
//In view file
echo $this->Html->url(array(
"controller" => "controller_name",
"action" => "action_name",
"ext" => "file_extension_name"
));
Also read Cakephp Media View
This is my ans :
$(document).ready(function(){
if('<?php echo $filename ?>' !=''){
window.location.href ='/files/<?php echo $filename ?>.xls';
}
});
</script>