Wordpress unable to save featured image - javascript

this is Nadeem I am a beginner on PHP and WordPress, I stuck on one point during custom plugin development, my problem is, I am unable to save Featured image and custom taxonomy tag and category from the frontend. In the meantime, I already Search on Google, StackOverflow, etc. too much for this error solution about this but unfortunately, this does not work and I am stuck at this point from the last 2 weeks.
This is my Plugin PHP code
/**
* The Template for displaying car archives, including the main car-data page which is a post type archive.
*
* Override this template by copying it to yourtheme/car_data/archive-car-data.php
*
* #author Shaikh Nadeem
* #package Car_Data
* #subpackage Car_Data/Templates
* #version 1.0.0
*/
class Car_Frontend_Form
{
function __construct()
{
add_shortcode( 'submit_car', array($this, 'submit_car') );
add_action( 'wp_enqueue_scripts', array( $this, 'my_enqueue' ) );
add_action( 'save_post_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_nopriv_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'init', array( $this, 'submit_car_data_post' ) );
}
public function submit_car() {
echo '<div id="submit_car_form">';
echo '<form id="cd_car" name="cd_car" class="cd_car" method="post" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data" >';
wp_nonce_field( "car-frontend-post" );
echo '<p><label for="title">Title</label><br />';
echo '<input type="text" id="title" value="" size="60" name="title" />';
echo '</p>';
echo '<p>';
echo '<label for="content">Post Content</label><br />';
echo '<textarea id="content" name="content" cols="40" rows="4"></textarea>';
echo '</p>';
echo '<p><label for="feature">Feature:</label><br />';
wp_dropdown_categories( "show_option_none=Feature&tab_index=3&taxonomy=feature&name=feature&id=feature&class=feature" ) .'</p>';
echo '<p><label for="make">Make:</label><br />';
wp_dropdown_categories( "show_option_none=Make&tab_index=4&taxonomy=make&name=make&id=make&class=make" ) .'</p>';
echo '<p><label for="post_tags">Tags</label><br />';
echo ' <input type="text" value="" size="60" name="post_tags" id="post_tags" /></p>';
echo '<p><label for="post_tags">Car Image</label><br />';
echo '<input type="file" name="file" id="file"></p>';
echo '<p align="left"><input type="submit" tabindex="6" id="submit_car" name="submit_car" /></p>';
echo '</form>';
echo '</div>';
return;
}
public function submit_car_data_post() {
if ( isset($_POST['title']) ) {
echo '<script>console.log("file error: '.$fileerror.'<br>");</script>';
$title = sanitize_text_field( $_POST['title'] );
$content = sanitize_text_field( $_POST['content'] );
$author_id = sanitize_text_field( $_POST['author_id'] );
$tags_input = sanitize_text_field( array($_POST['post_tags']) );
$feature = sanitize_text_field( array($_POST['feature']) );
$make = sanitize_text_field( array($_POST['make']) );
// $image = $_POST['file'];
$args = array(
'post_title' => $title,
'post_content' => $content,
'tags_input' => $_POST['post_tags'],
'author' => $author_id,
'post_status' => 'publish',
'post_type' => 'car-data',
'tax_input' => array(
$feature,
$make
),
// 'post_category' => array(
// 'feature' => array($_POST['feature']),
// 'make' => array($_POST['make'])
// )
);
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'car-frontend-post') ) {
return;
}
if( is_wp_error( $posts ) ){
echo json_encode( $posts->get_error_messages() );
}
// save frontend Post
$posts = wp_insert_post( $args );
// save frontend Texonomy
wp_set_object_terms( $posts, $feature, 'feature' );
wp_set_object_terms( $posts, $make, 'make' );
// save Atachment on featured image for the current custom post
$uploaddir = wp_upload_dir();
$file = $_FILES[$image];
$uploadfile = $uploaddir['path'] . '/' . basename( $file );
move_uploaded_file( $_FILES['file']['tmp_name'], $uploaddir['path'] . '/' . $filename );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => preg_replace('/\.[^.]+$/', '', $filename),
'post_excerpt' => preg_replace('/\.[^.]+$/', '', $filename),
'post_status' => 'inherit',
'post_type' => 'attachment',
'menu_order' => $_i + 1000,
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata($attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
wp_die();
}
}
public function my_enqueue() {
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
}
and i use javascript for the ajax alert message when form is submit
jQuery(document).ready(function($) {
$('.cd_car').on('submit', function(event) {
event.preventDefault();
var message = document.getElementById("file").value;
var empt = document.forms["cd_car"]["title"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
else
{
$.ajax({
type: 'post',
// url : ajax_object.ajaxurl,
data : $('.cd_car').serialize(),
success : function(data){
alert(message);
console.log(data);
},
error : function(data){
alert(message);
alert('fail');
}
});
}
});
});
Also i have there one error on this line code if ( isset($_POST['title']) ) unable to use submit key on isset post only title is working here.

I believe your issue is due to sanitize_text_field( array( .. )). sanitize_text_field only accepts strings as the parameter, so I assume by sending in an Array it's actually always seeing the string "Array" - not your POST values.
To sanitize the array, could do something like:
$tags_input = array();
if ( isset($_POST['post_tags']) && !empty($_POST['post_tags']) ) {
foreach ($_POST['post_tags'] as $val)
$tags_input[] = sanitize_text_field( $val );
}
// [ .. repeat for feature & make .. ]
Or, if they're single values only (not arrays), simply remove the array wrapper.

Related

Search query with filter

Thanks to the help of stack overflow I was able to make my filter work(Ajax filter for wordpress) but now I want to add a search input that search the titles of my posts (a custom post type called 'Contratistas').
So I have a few questions:
My form for my filter has POST, but the search (i've seen examples) always has GET, so, should I have two separete forms? If so, is there a way for submiting my search without a button? this is my code:
<form id="searchform" method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="text" class="search-field mb-3" name="s" placeholder="Search" value="<?php echo get_search_query(); ?>">
<input type="submit" value="Search" class="mb-3">
</form>
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<div class="titulo mb-3">
<h3>Región</h3>
</div>
<?php
if( $terms = get_terms( array( 'taxonomy' => 'region', 'orderby' => 'name' ) ) ) :
echo '<select name="filtroRegion"><option value="">Seleccione una región</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<div class="titulo my-3">
<h3>Industrias</h3>
</div>
<?php
if( $terms = get_terms( array( 'taxonomy' => 'industria', 'orderby' => 'name' ) ) ) :
echo '<select name="filtroIndustria"><option value="">Seleccione una industria</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<button class="my-3 filtrar">Filtrar</button>
<button>Limpiar filtros</button>
<input type="hidden" name="action" value="myfilter">
</form>
As you can see i have two buttons but i only want the last one ('Filtrar')
I have no idea how to implement the search with the filters so that i can put my results in the same fashion as the one i get from the dropdowns.
Here is my filter:
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'post_per_page' => -1,
'post_type' => 'contratista'
);
if (!empty($_POST['filtroRegion']) || !empty($_POST['filtroIndustria'])) {
$args['tax_query'] = array();
if (!empty($_POST['filtroRegion'])) {
$args['tax_query'][] = array(
'taxonomy' => 'region',
'terms' => $_POST['filtroRegion']
);
}
if (!empty($_POST['filtroIndustria'])) {
$args['tax_query'][] = array(
'taxonomy' => 'industria',
'terms' => $_POST['filtroIndustria']
);
}
if (count($args['tax_query']) > 1) {
$args['tax_query']['relation'] = 'AND';
}
}
$query = new WP_Query($args);
And my JQuery:
jQuery(function($) {
$('#filter').submit(function() {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: $('#filter :input').filter(function(index, element) { return $(element).val() != ''; }).serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function(xhr) {
filter.find('.filtrar').text('Procesando...'); // changing the button label
},
success: function(data) {
filter.find('.filtrar').text('Filtrar'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
}
}
Any help or guidance will be very appreciated. Thanks
I got it! Here's my working code in case somebody else needs it!
The answer was VERY simple! I only had to add this:
's' => $_POST['s']
Here is my function
function misha_filter_function(){
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'post_per_page' => -1,
'post_type' => 'contratista',
's' => $_POST['s'],
);
//Same code as before:
if( !empty($_POST['filtroRegion']) || !empty($_POST['filtroIndustria']) ){
$args['tax_query'] = array();
if(!empty($_POST['filtroRegion']) ){
$args['tax_query'][] = array(
'taxonomy' => 'region',
'terms' => $_POST['filtroRegion']
);
}
}
$query = new WP_Query( $args );
//my post
And my form:
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<h3>Buscar</h3>
<input type="text" class="search-field mb-3" name="s" placeholder="Busqueda por nombre" value="<?php echo get_search_query(); ?>">
<div class="titulo mb-3">
<h3>Región</h3>
</div>
<?php
if( $terms = get_terms( array( 'taxonomy' => 'region', 'orderby' => 'name' ) ) ) :
echo '<select name="filtroRegion"><option value="">Seleccione una región</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>

i have a problem trying to add a upload media button to a custom metabox

I really dont see were the problem is, when tring to use my media button on wordpress. here is my source code.
php:
<?php
/**
* #package OverviewPlugin
*/
namespace Inc\Base;
use Inc\Api\SettingsApi;
use Inc\Base\BaseController;
use Inc\Api\Callbacks\AdminCallbacks;
use Inc\Api\Callbacks\WorkerCallbacks;
/**
*
*/
class WorkerController extends BaseController
{
public $callbacks;
public $settings;
public function register()
{
if ( ! $this->activated( 'worker_manager' ) ) return;
$this->settings = new SettingsApi();
$this->callbacks = new WorkerCallbacks();
add_action( 'init', array( $this, 'worker_cpt' ) );
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
add_action( 'save_post', array( $this, 'save_meta_box' ) );
add_action( 'manage_worker_posts_columns', array( $this, 'set_custom_columns' ) );
add_action( 'manage_worker_posts_custom_column', array( $this, 'set_custom_columns_data' ), 10, 2 );
add_filter( 'manage_edit-worker_sortable_columns', array( $this, 'set_custom_columns_sortable' ) );
$this->setShortcodePage();
add_shortcode( 'worker-display', array( $this, 'worker_display' ) );
add_action('admin_enqueue_scripts', array($this, 'my_admin_scripts'));
add_action('admin_enqueue_scripts', array($this,'my_admin_scripts'));
add_action('admin_enqueue_styles',array($this,'my_admin_styles'));
}
function my_admin_scripts() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('my-upload', WP_PLUGIN_URL.'/overview-plugin/assets/worker.min.js', array('jquery','media-upload','thickbox'));
wp_enqueue_script('my-upload');
}
function my_admin_styles() {
wp_enqueue_style('thickbox');
}
public function worker_display()
{
ob_start();
echo "<link rel=\"stylesheet\" href=\"$this->plugin_url/assets/display.min.css\" type=\"text/css\" media=\"all\" />";
require_once( "$this->plugin_path/templates/display.php" );
echo "<script src=\"$this->plugin_url/assets/display.min.js\"></script>";
return ob_get_clean();
}
public function render_features_box($post)
{
wp_nonce_field( 'overview_worker', 'overview_worker_nonce' );
$data = get_post_meta( $post->ID, '_overview_worker_key', true );
$name = isset($data['name']) ? $data['name'] : '';
$description = isset($data['description']) ? $data['description'] : '';
$image = isset($data['image']) ? $data['image'] : '';
$position = isset($data['position']) ? $data['position'] : '';
$github = isset($data['github']) ? $data['github'] : '';
$linkedin = isset($data['linkedin']) ? $data['linkedin'] : '';
$xing = isset($data['xing']) ? $data['xing'] : '';
$facebook = isset($data['facebook']) ? $data['facebook'] : '';
$approved = isset($data['approved']) ? $data['approved'] : false;
$featured = isset($data['featured']) ? $data['featured'] : false;
?>
<p>
<label class="meta-label" for="overview_worker_name">Name</label>
<input type="text" id="overview_worker_name" name="overview_worker_name" class="widefat" value="<?php echo esc_attr( $name ); ?>">
</p>
<p>
<label class="meta-label" for="overview_worker_description">Short Description</label>
<input type="text" id="overview_worker_description" name="overview_worker_description" class="widefat" value="<?php echo esc_attr( $description ); ?>">
</p>
<p>
<label class="meta-label" for="overview_worker_image">Image</label>
<input id="upload_image" type="text" size="36" name="upload_image" value="<?php echo esc_attr( $image ); ?>" />
<input id="upload_image_button" type="button" value="Upload Image" />
</p>
js:
jQuery(document).ready( function( $ ) {
$('#upload_image_button').click(function() {
formfield = $('#upload_image').val();
tb_show( '', 'media-upload.php?type=image&TB_iframe=true' );
window.send_to_editor = function(html) {
imgurl = $(html).attr('src');
$('#upload_image').val(imgurl);
tb_remove();
}
return false;
});
});
i am sorry if it's a lot of code but i really don't know where i went wrong. my idea is to have a button that does the same function as the upload media button. i have seen lots of refrences and still couldn't get the code running.
When i click the upload button an i open my chrome inspector i receive the following error
worker.min.js:6 Uncaught ReferenceError: formfield is not defined
at HTMLInputElement.<anonymous> (worker.min.js:6)
at HTMLInputElement.dispatch (load-scripts.php?c=1&load[chunk_0]=jquery-core,jquery-migrate,utils,underscore,thickbox,shortcode,media-upload,moxiejs,plupload&ver=5.3.2:3)
at HTMLInputElement.r.handle (load-scripts.php?c=1&load[chunk_0]=jquery-core,jquery-migrate,utils,underscore,thickbox,shortcode,media-upload,moxiejs,plupload&ver=5.3.2:3)
Either you can do this
formfield = $('#upload_image').val();
becasue $image is a php variable you can not get its value in jquery like this directly.

getElementById returns empty from WP Variable

So I have this widget that I coded base on wordpress standard. I declared a sort of variables to be use both backend and frontend purposes.
public function widget( $args, $instance ) {
global $post;
$sid = $instance['id'];
$name = $instance['name'];
$args = array( 'post_type' => 'content_manager','post_id' => $sid);
$query = new WP_Query( $args );
echo $args['before_widget'];
echo $args['after_widget'];
}
public function form( $instance ) {
global $post;
$args = array( 'post_type' => 'content_manager'); ....
$loop = new WP_Query( $args );
$title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'New title', 'text_domain' );
$sid = ! empty( $instance['id'] ) ? $instance['id'] : esc_html__( 'New ID', 'text_domain' );
$name = ! empty( $instance['name'] ) ? $instance['name'] : esc_html__( 'Empty Content', 'text_domain' );
I am using the variables to get the values in javascript
<script>
function defineValue(sel)
{
var title = sel.options[sel.selectedIndex].text;
var id = sel.options[sel.selectedIndex].value;
document.getElementById("<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>").value = title;
document.getElementById("<?php echo esc_attr( $this->get_field_name( 'id' ) ); ?>").value = id;
document.getElementById("<?php echo esc_attr( $this->get_field_name( 'name' ) ); ?>").value = title;
}
</script>
When I load the widget, the inputs and other options displays the names and IDs but in Javascript returns empty unless If I save it first.
I tried to test it
<?php echo esc_attr( $this->get_field_name( 'id' ) ); ?>
and this is the result
widget-content-loader-__i__-id
Why is that happen?
Notes:
First Inputs and other elements have ids and other attributes from that variables when I check in the DOM
<input class="widefat" name="widget-content-loader[21][title]" id="widget-content-loader-21-title" value="New title" type="text">
From this this script:
<input
class="widefat"
name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
type="text"
id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
value="<?php echo esc_attr( $title ); ?>">
Thanks in advance
Javascript cant get value unless it is loaded into DOM,
Make sure that the elements are loaded before calling definevalue()

Duplicate posts on AJAX call in WordPress

I've attempted to setup a 'load more' button in WordPress. Simple idea, you press the button and it loads more posts using AJAX without reloading the page or needing to use pagination.
I followed a previous article on SO and have managed to get it to mostly work.
So far, I've been able to get additional posts loading fine, but for some reason, they are being duplicated. I had a look in the Networks tab and it seems each time I press the button, admin-ajax.php runs twice which I suspect is what's causing the duplication. Unfortunately, I'm not too sure what I need to change to resolve this.
It would also be really helpful to know how to get this working for custom post types as well as normal posts. On my website, I've got two post types, Standard blog posts and a custom 'Projects' post type. Each has its own page and own loop, how would I modify the above to get it to work for both? Would I need to write out the whole thing twice or maybe It's something simpler?
Any ideas guys?
Here is the HTML:
<section id="ajax-posts" class="layout">
<?php get_template_part( 'content', 'blog' ); ?>
</section>
<div class="load-more layout">
<a id="more_posts" class="button"><span class="icon-plus"></span></a>
</div>
Here is the main loop:
<?php
$postsPerPage = 1;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_post_thumbnail();?>
<div class="inner-text">
<h4 class="post-title"><?php the_title(); ?></h4>
<h5><span class="icon-calendar"></span> <?php the_date(); ?></h5>
<?php the_excerpt(); ?>
Read More<span class="icon-arrow-right2"></span>
</div>
</article>
<?php endwhile; wp_reset_postdata(); ?>
Here is my functions.php:
function wpt_theme_js() {
wp_enqueue_script( 'bigredpod-script', get_template_directory_uri() . '/js/main.js', array( 'jquery' ), '', true );
wp_localize_script( 'bigredpod-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'bigredpod'),
));
}
wp_localize_script( 'bigredpod-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'bigredpod'),
));
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 1;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'posts_per_page' => $ppp,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .=
'<article id="post-'. get_the_ID().'" class="'. implode(' ', get_post_class()) .'">
'.get_the_post_thumbnail().'
<div class="inner-text">
<h4 class="post-title">'.get_the_title().'</h4>
<h5><span class="icon-calendar"></span> '.get_the_date().'</h5>
<p>'.get_the_excerpt().'</p>
Read More<span class="icon-arrow-right2"></span>
</div>
</article>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax'); ?>
Here is my JS:
jQuery(document).ready(function($) {
var ppp = 1; // Post per page
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").addClass('posts_loading');
} else{
$("#more_posts").removeClass('posts_loading').addClass('no_more_posts');
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
});
You have put twice
wp_localize_script( 'bigredpod-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'bigredpod'),
));
In your wpt_theme_js() function. This is probably what causes the ajax to load twice.

How to use images to change dropdown selection?

what I'm trying to accomplish is to have image thumbnails replace the dropdown box in a woocommerce variation product page. The way I went to trying to get that to work is when a user clicks on an variation product image, the (will be hidden) dropdown box will change to the correct value just as if the user had interacted with the dropdown box itself. the file I'm working with is variable.php.
Here is a snippet of the code. All my custom codes start with the option tag loop just before the closing Select tag.
$loop = 0; foreach ( $attributes as $name => $options ) : $loop++; $countimg = 0;?>
<select id="<?php echo esc_attr( sanitize_title( $name ) ); ?>" name="attribute_<?php echo sanitize_title( $name ); ?>" >
<option value=""><?php echo __( 'Choose an option', 'woocommerce' ) ?>…</option>
<?php
if ( is_array( $options ) ) {
if ( isset( $_REQUEST[ 'attribute_' . sanitize_title( $name ) ] ) ) {
$selected_value = $_REQUEST[ 'attribute_' . sanitize_title( $name ) ];
} elseif ( isset( $selected_attributes[ sanitize_title( $name ) ] ) ) {
$selected_value = $selected_attributes[ sanitize_title( $name ) ];
} else {
$selected_value = '';
}
// Get terms if this is a taxonomy - ordered
if ( taxonomy_exists( $name ) ) {
$orderby = wc_attribute_orderby( $name );
switch ( $orderby ) {
case 'name' :
$args = array( 'orderby' => 'name', 'hide_empty' => false, 'menu_order' => false );
break;
case 'id' :
$args = array( 'orderby' => 'id', 'order' => 'ASC', 'menu_order' => false, 'hide_empty' => false );
break;
case 'menu_order' :
$args = array( 'menu_order' => 'ASC', 'hide_empty' => false );
break;
}
$terms = get_terms( $name, $args );
$count = 1;
foreach ( $terms as $term ) {
if ( ! in_array( $term->slug, $options ) )
continue;
echo '<option id="' . $count . '" value="' . esc_attr( $term->slug ) . '" ' . selected( sanitize_title( $selected_value ), sanitize_title( $term->slug ), false ) . '>' . apply_filters( 'woocommerce_variation_option_name', $term->name ) . '</option>';
$count++;}
} else {
foreach ( $options as $option ) {
echo '<option id="' . $count . '" value="' . esc_attr( sanitize_title( $option ) ) . '" ' . selected( sanitize_title( $selected_value ), sanitize_title( $option ), false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) ) . '</option>';
$count++;}
}
}
?>
</select>
<div>
<?php foreach ( $available_variations as $available_variation ) {
$countimg++;
$image_links = $available_variation['image_link'];
echo '<img id="' . $countimg . '" src="' . $image_links . '" onclick="selectVariationOption(this.id)" style="height:65px; margin-bottom:5px;">';
}?>
</div>
<script>
function selectVariationOption(clicked_id) {
document.getElementById("<?php echo esc_attr( sanitize_title( $name ) ); ?>").selectedIndex = clicked_id;
}
</script>
<?php
if ( sizeof($attributes) == $loop )
echo '<a class="reset_variations" href="#reset">' . __( 'Clear selection', 'woocommerce' ) . '</a>';
?>
<?php endforeach;?>
</div>
</div>
What I did here was I added a numerical ID to the option tags and increases with each additional option available. I then showed the available image variations and added a numerical ID that looped to match the corresponding option ID. Finally, I used a simple javascript that when an image is clicked, the dropdown box changes to the correct selectedIndex. The problem is, the page doesn't react to the changes as if the dropdown box was directly interacted with. In short, nothing happens but the dropdown box changing visual value. I want it so that clicking on the image would be the exact same as clicking on an option in the dropdown box.
Let me know if you need more clarification or information. Thanks in advance!
Using the Variation Swatches and Photos plugin worked. Just had to go in and edit the plugin's variable.php to show all the information that was missing from my original variable.php file. Now I just have to spend a couple hours editing each product.

Categories