I m trying to implement query with custom fields on my local wordpress website.
All works like a charm except when I check the radio button, this one want to be checked...
Can you help me please ? thanks for your reply.
<div id="archive-filters">
<?php foreach( $GLOBALS['my_query_filters'] as $key => $name ):
$field = get_field_object($key);
if( isset($_GET[ $name ]) ) {
$field['value'] = explode(',', $_GET[ $name ]);
}
// create filter
?>
<div class="filter" data-filter="<?php echo $name; ?>">
<?php create_field( $field ); ?>
</div>
<?php endforeach; ?>
</div>
<script type="text/javascript">
(function($) {
// change
$('#archive-filters').on('change', 'input[type="radio"]', function(){
var url = '';
args = {};
$('#archive-filters .filter').each(function(){
var filter = $(this).data('filter'),
vals = [];
$(this).find('input:checked').each(function(){
vals.push( $(this).val() );
});
// append to args
args[ filter ] = vals.join(',');
});
// update url
url += '?';
// loop over args
$.each(args, function( name, value ){
url += name + '=' + value + '&';
});
// remove last &
url = url.slice(0, -1);
// reload page
window.location.replace( url );
});
})(jQuery);
</script>
Related
I have styled my select items using JQuery, which outputs the items in an unordered list. This is working. I've used some javascript to create in infinite scroll effect on the unordered list. The infinite scroll basically repeats the entire list resulting in two identical sets of list items. However, the cloned set list items are not clickable and thus the form does not render any results when clicking the cloned list items.
Link to the select in question (try the Emotional Quality Select) - http://dev.chrislamdesign.com/shortwave/sample-page/
Link to codepen infinite scroll - https://codepen.io/doctorlam/pen/oKgRvO
Here's my PHP
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<div class="container d-flex justify-content-between">
<div class="row" style="width: 100%">
<?php
if( $terms = get_terms( array('hide_empty' => false,'taxonomy' => 'emotional_quality', 'orderby' => 'name' ) ) ) : ?>
<div id="emotional" class="col-md-4">
<?php
echo '<select class="form-submit" name="categoryfilter2"><option value="">Emotional Quality</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>'; ?>
</div>
<?php endif;
if( $terms = get_terms( array( 'hide_empty' => false,'taxonomy' => 'genre', 'orderby' => 'name' ) ) ) : ?>
<div id="genre" class="col-md-4">
<?php echo '<select class= "form-submit" name="categoryfilter"><option value="">Select genre...</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>'; ?>
</div>
<?php endif;
if( $terms = get_terms( array( 'hide_empty' => false,'taxonomy' => 'cinematic_style', 'orderby' => 'name' ) ) ) : ?>
<div id="cinematic" class="col-md-4">
<?php echo '<select class="form-submit" name="categoryfilter3"><option value="">Cinematic Style</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>'; ?>
</div>
<?php endif;
?>
<!-- <button>Apply filter</button> -->
<input type="hidden" name="action" value="myfilter">
</div><!-- row -->
</div>
</form>
Here's the Javascript to style the select
<script>
jQuery(document).ready(function($){
$('select').each(function(){
var $this = $(this), numberOfOptions = $(this).children('option').length;
$this.addClass('select-hidden');
$this.wrap('<div class="select"></div>');
$this.after('<div class="select-styled"></div>');
var $styledSelect = $this.next('div.select-styled');
$styledSelect.text($this.children('option').eq(0).text());
var $list = $('<ul />', {
'class': 'select-options'
}).insertAfter($styledSelect);
$list.wrap('<div class="scroll-container"><div class="wrap-container"></div></div>');
for (var i = 0; i < numberOfOptions; i++) {
$('<li />', {
text: $this.children('option').eq(i).text(),
rel: $this.children('option').eq(i).val()
}).appendTo($list);
}
var $listItems = $list.children('li');
$styledSelect.click(function(e) {
e.stopPropagation();
$('div.select-styled.active').not(this).each(function(){
$(this).removeClass('active').next('.scroll-container').hide();
});
$(this).toggleClass('active').next('.scroll-container').toggle();
});
$listItems.click(function(e) {
e.stopPropagation();
$styledSelect.text($(this).text()).removeClass('active');
$this.val($(this).attr('rel'));
$('.scroll-container').hide();
//console.log($this.val());
});
$(document).click(function() {
$styledSelect.removeClass('active');
$('.scroll-container').hide();
});
});
});
</script>
Here's the Javascript for the infinite scroll
<script>
jQuery(function($){
$('#emotional .wrap-container').attr('id', 'wrap-scroll-1');
$('#emotional .wrap-container ul').attr('id', 'ul-scroll-1');
$('#genre .wrap-container').attr('id', 'wrap-scroll-2');
$('#genre .wrap-container ul').attr('id', 'ul-scroll-2');
$('#cinematic .wrap-container').attr('id', 'wrap-scroll-3');
$('#cinematic .wrap-container ul').attr('id', 'ul-scroll-3');
});
</script>
<!-- Infiinite scroll for emotional quality-->
<script>
var scrollW = document.getElementById("wrap-scroll-1");
var scrollUl = document.getElementById("ul-scroll-1");
var itemsScrolled,
itemsMax,
cloned = false;
var listOpts = {
itemCount: null,
itemHeight: null,
items: []
};
function scrollWrap() {
var scrollW = document.getElementById("wrap-scroll-1");
var scrollUl = document.getElementById("ul-scroll-1");
itemsScrolled = Math.ceil(
(this.scrollTop + listOpts.itemHeight / 2) / listOpts.itemHeight
);
if (this.scrollTop < 1) {
itemsScrolled = 0;
}
listOpts.items.forEach(function(ele) {
ele.classList.remove("active");
});
if (itemsScrolled < listOpts.items.length) {
listOpts.items[itemsScrolled].classList.add("active");
}
if (itemsScrolled > listOpts.items.length - 3) {
var node;
for (_x = 0; _x <= itemsMax - 1; _x++) {
node = listOpts.items[_x];
if (!cloned) {
node = listOpts.items[_x].cloneNode(true);
}
scrollUl.appendChild(node);
}
initItems(cloned);
cloned = true;
itemsScrolled = 0;
}
}
function initItems(scrollSmooth) {
var scrollUl = document.getElementById("ul-scroll-1");
var scrollW = document.getElementById("wrap-scroll-1");
listOpts.items = [].slice.call(scrollUl.querySelectorAll("li"));
listOpts.itemHeight = listOpts.items[0].clientHeight;
listOpts.itemCount = listOpts.items.length;
if (!itemsMax) {
itemsMax = listOpts.itemCount;
}
if (scrollSmooth) {
var scrollW = document.getElementById("wrap-scroll-1");
var seamLessScrollPoint = (itemsMax - 3) * listOpts.itemHeight;
scrollW.scrollTop = seamLessScrollPoint;
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var scrollW = document.getElementById("wrap-scroll-1");
initItems();
scrollW.onscroll = scrollWrap;
});
</script>
AJAX CALL
<script>
jQuery(function($){
jQuery('.select-options li').click(function() {
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
</script>
The original list items trigger the form and return the correct results. The cloned list items don't. I think it has to do with the identical rel values but am not sure.
Changing your ajax call to the below suggested way should make the click work for you:
<script>
jQuery(function($){
jQuery('body').on('click', '.select-options li', function() {
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
</script>
The reason as to why this should work is because now the click event is bound on the class irrespective of whether the element with that class was loaded in DOM loading or after the DOM was loaded completely.
The direct call to .click or in the format jQuery('.select-options li').on('click', function(){}); only binds event to elements loaded before the DOM was ready.
I want to achieve this in below mention code need
i want to highlight text in auto complete same like pic i added above
<?php
$query = isset($_GET['query']) ? $_GET['query'] : FALSE;
global $wpdb;
// escape values passed to db to avoid sql-injection
$depts = $wpdb->get_results( "SELECT * FROM wp_paklog_service WHERE service_name LIKE '".$query."%'" );
$suggestions = array();
$data = array();
foreach($depts as $row) {
$suggestions[] = $row->service_name;
$data[] = $row->id;
}
json_encode ($suggestions);
?>
//this is js code
var obj = <?php echo json_encode($suggestions); ?>;
jQuery(".search-services").autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + jQuery.ui.autocomplete.escapeRegex( request.term ), "i" );
response( jQuery.grep( obj, function( item ){
return matcher.test( item );
}) );
}
I have a question about wordpress, I just added a button called Add Slider in Add/Edit Post Page.
here's my code in my function.php :
//Add button to create slider
add_action('media_buttons','add_my_media_button',15);
function add_my_media_button(){
echo 'Add Slider';
}
function include_media_button_js_file(){
wp_enqueue_script('media_button',get_bloginfo('template_directory').'/js/media_button.js',array('jquery'),'1.0',true);
}
add_action('wp_enqueue_media','include_media_button_js_file');
and this my media_button.js code
jQuery(function($){
$(document).ready(function(){
$('#insert-my-media').click(open_media_window);
})
function open_media_window(){
if (this.window === undefined) {
this.window = wp.media({
title: 'Insert a media',
library: {type:'image'},
multiple: true,
button: {text:'Insert'}
});
var self = this; //needed to retrieve the function below
this.window.on('select',function(){
var files = self.window.state().get('selection').toArray();
var values;
for (var i = 0; i < files.length; i++) {
var file = files[i].toJSON();
if(values===undefined){
var values = file.url;
}
else{
var values = values+','+file.url;
}
};
wp.media.editor.insert(values);
});
}
this.window.open();
return false;
}
});
after user select the pictures in media window and press Insert button it will add url value of pictures to content editor post box.
My question is how to add this value automatically on custom fields box and add/update that automatically without click add custom field button.
So user can add / update custom fields for that pictures url without view/ check custom fields to view in post editor on Screen Options in wordpress.
Please help me for this question, Thanks.
I modify my jquery / js like this..
$(document).ready(function(){
// $('#insert-my-media').click(open_media_window);
if($('#images_id').val() != '' && $('#images_url').val() != ''){
$('#open_media').text("Edit Slider");
}
$('#open_media').click(function(e){
e.preventDefault();
var target = $('#images_id');
var target_url = $('#images_url');
var btnSave = $('#publishing-action input.button');
if(target.val() == '' && target_url.val() == ''){
var wpmedia = wp.media({
title: 'Insert a media',
library: {type:'image'},
multiple: true,
button: {text:'Insert'}
});
wpmedia.on('select', function(){
var ids = [];
var urls = [];
var models = wpmedia.state().get('selection').toArray();
for (var i = 0; i < models.length; i++) {
var file = models[i].toJSON();
ids.push(file.id);
urls.push(file.url);
};
target.val(ids.join(","));
target_url.val(urls.join(","));
$('#deleting_slider').val("");
$('#open_media').text("Adding...");
btnSave.click();
});
wpmedia.open();
}else{
wp.media.gallery
.edit('[gallery ids="'+ target.val() +'" urls="'+ target_url.val() +'"]')
.on('update', function(g){
var ids = [];
var urls = [];
for (var i = 0; i < g.models.length; i++) {
var file = g.models[i].toJSON();
ids.push(file.id);
urls.push(file.url);
};
target.val(ids.join(","));
target_url.val(urls.join(","));
$('#deleting_slider').val("");
$('#open_media').text("Editing...");
btnSave.click();
});
}
});
$('#save_desc').click(function(e){
e.preventDefault();
var target = $('#desc_editor');
var btnSave = $('#publishing-action input.button');
target.val(target.val());
btnSave.click();
});
$('#delete_slider').click(function(e){
e.preventDefault();
/*var target = $('#images_id');
var target_url = $('#images_url');*/
var btnSave = $('#publishing-action input.button');
/*target.val("");
target_url.val("");*/
$('#deleting_slider').val("Deleting...");
$('#delete_slider').text("Deleting...");
btnSave.click();
});
});
and then I make file called metabox.php to create metabox
<?php
function koplan_add_metabox(){
add_meta_box(
'koplan_metabox_gallery',
'Slider Gallery',
'koplan_show_metabox',
'post'
);
}
function koplan_add_maps_metabox(){
add_meta_box(
'koplan_metabox_maps',
'Maps Descriptions',
'koplan_show_maps_metabox',
'post'
);
}
function koplan_show_metabox($post){
$ids = get_post_meta($post->ID, 'gallery_images', true);
$urls = get_post_meta($post->ID,'images',true);
?>
Add Slider
<hr>
<input type="hidden" name="gallery_images" id="images_id" value="<?php echo $ids; ?>">
<input type="hidden" name="gallery_urls" id="images_url" value="<?php echo $urls; ?>">
<input type="hidden" name="deleting_slider_post_meta" id="deleting_slider" value="<?php echo $urls; ?>">
<?php
if($ids=="" and $urls==""){
return;
}
else{
echo do_shortcode('[gallery ids="'.$ids.'" urls="'.$urls.'"]');
}
?>
<hr>
Delete Slider
<?php
}
function koplan_save_gallery_metabox($post_id){
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if(! isset($_POST['gallery_images']) && !isset($_POST['gallery_urls'])){
return;
}
$ids = sanitize_text_field( $_POST['gallery_images'] );
$urls = sanitize_text_field( $_POST['gallery_urls'] );
$terms = wp_get_object_terms( $post_id, 'category', array( 'fields' => 'names' ) );
/*$termsname = $terms[0]->name;*/
if(strlen($terms[1]) > strlen($terms[0])){
$term = $terms[1];
}
else{
$term = $terms[0];
}
$sldata = '<slider images="'.$term.'" />';
update_post_meta($post_id, 'slider', $sldata);
update_post_meta($post_id, 'gallery_images', $ids);
update_post_meta($post_id, 'images', $urls);
if(isset($_POST['deleting_slider_post_meta']) && $_POST['deleting_slider_post_meta'] != ""){
delete_post_meta($post_id, 'slider', $sldata);
delete_post_meta($post_id, 'gallery_images', $ids);
delete_post_meta($post_id, 'images', $urls);
}
}
function koplan_show_maps_metabox($post){
$desc = get_post_meta($post->ID,'mapsdesc',true);
if($desc!=""){
?>
<textarea name="maps_descriptions" id="desc_editor" placeholder="Insert Descriptions Here" class="wp-editor-area" cols="40" autocomplete="off" style="height:320px; width:100%;"><?php echo $desc; ?></textarea>
<?php
}else{
?>
<textarea name="maps_descriptions" id="desc_editor" placeholder="Insert Descriptions Here" class="wp-editor-area" cols="40" autocomplete="off" style="height:320px; width:100%;"></textarea>
<?php
}
?>
<hr>
Save
<?php
}
function koplan_save_maps_desc_metabox($post_id){
if (define('DOING_AUTOSAVE') && DOING_AUTOSAVE){
return;
}
if(!isset($_POST['maps_descriptions'])){
return;
}
$desc = $_POST['maps_descriptions'];
update_post_meta($post_id,'mapsdesc',$desc);
}
add_action( 'add_meta_boxes', 'koplan_add_metabox' );
add_action('add_meta_boxes','koplan_add_maps_metabox');
add_action( 'save_post', 'koplan_save_gallery_metabox' );
add_action( 'save_post', 'koplan_save_maps_desc_metabox' );
?>
I said problem solved, case closed. Thanks all, thanks stackoverflow
Hi i have small project in which i have tab 1 i.e FahrzeugeWidget and tab 2 i.e FahrzeugeWidgetEdit. In 1 tab i have list and in second tab i have checkbox list from which i want to select what users want and then then switch to tab1 after submit button and show only values selected from checkbox.I used jQuery selector for same.Every thing is running fine. Only i am not able to get the values selected from checkbox after submit button.There is only small mistake i as doing not able to identify.Here is fiddle:demo So i should only get those values selected from checkbox. Here is my code:
dashboard.php
if($param['aktion'] == 'save-widget-vehicle')
{
$page['register-fahrzeuge'] = array(
1 => array( 'Fahrzeug','aktiv',$page['script'],''),
0 => array( 'Edit-Fahrzeug','enabled',$page['script'],'',''),
);
$opts = !empty($param['filterOpts']) ? $param['filterOpts'] : array();
$tmp = array();
foreach ($opts as $opt) {
$tmp[] = '"'.$opt.'"';
}
$query =
'SELECT Fahrzeuge.dsnr,name
FROM Fahrzeuge
INNER JOIN ohne_fahrzeuge ON Fahrzeuge.dsnr = ohne_fahrzeuge.dsnr
WHERE Fahrzeuge.name IN ('.implode(",", $tmp).')';
$result = mysql_query($query, $myConnection);
$data = array();
$html = '<table width="538" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>
<div>'.CreateRegister($page['register-news']).'</div>
'.CreateMessage().'
<div class="cont-liste-verlauf register"> ';
while($row = mysql_fetch_array($result)){
//$news_result = $fahrzeuge['name'];
$html .= '<table id="fahrzeuge">
<tr>
<td>
'. $data[] = $row .'
</td>
</tr> ';
}
$html .= '</table>
</div>
</td>
</tr>
</table>';
$return = array(
'status' => 1,
'html' => $html
);
echo json_encode($return);
die();
$param['aktion'] = 'get-widget-vehicle';
}
dashboard.js
function getFahrzeuge() {
var opts = [];
$("input[type=checkbox]").each(function () {
if (this.checked) {
opts.push($(this).attr("id"));
}
});
return opts;
}
function saveFahrzeugeWidget(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts, 'aktion' : 'save-widget-vehicle'},
success: function(data){
// $('#fahrzeuge').html(makeTable(records));
$('#fahrzeuge').html(data.html);
},
error: function(data){
alert('error' + data);
}
});
}
$('#fahrzeuge .butt-rahmen').live('click', function(){
if($(this).attr('id') == 'submitId')
var opts = getFahrzeuge();
saveFahrzeugeWidget(opts);
// $("#regl1").show();
// $("#regl1").hide();
});
var allFahrzeuge = [];
$("input[type=checkbox]").each(function(){
allFahrzeuge.push($(this)[0].id)
})
I don't know if this solves your problem but which JQuery version are you using? The JQuery function .live() is depricated since version 1.9. You must use .on() instead. May you don't get the values because the action isn't triggered by the use of the live() function?
I have a javascript dropdown on website, here is the code-
<?php
function get_request_uri_without_page() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
$request = explode('/page/',$pageURL);
$request = explode('?', $request[0]);
return $request[0];
}
?>
<form action="<?php echo get_request_uri_without_page(); ?>" method="get" id="catselect" class="form-archive-140">
<!-- DROP DOWN HERE -->
<?php global $jtCatId; $jtCatId = true; wp_dropdown_categories('show_count=1&hierarchical=1&child_of=140&class=selectmenu&id=cat&show_option_none=Please Choose...'); ?>
<script type="text/javascript">
<!--
var dropdown = document.getElementById("cat");
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo get_request_uri_without_page(); ?>?cat="+dropdown.options[dropdown.selectedIndex].value;
}
}
dropdown.onchange = onCatChange;
-->
</script>
The output of this dropdown is a list of posts filtered by location, however the URL structure is as follows-
thewebsite/themaincategory?cat=141
I would like to replace the category id at the end with the category name, when I replace dropdown.selectedIndex to "text" the dropdown does not work, it doesn't give an error it just doesn't do anything.
Do I need to do a rewrite in the htaccess or is their a way to get the above code working.
I would like to apologise in advance if this is a stupid question, I am new to javascript and just trying to find my way.
Here is a working example of the above mentioned-
http://www.theweddingdirectory.co.za/professional-wedding-photographers
try something like this
var cat= document.getElementById("cat");
var text = cat.options[cat.selectedIndex].text;
EDITED CODE
function onCatChange() {
if ( dropdown.options[dropdown.selectedIndex].value > 0 ) {
location.href = "<?php echo get_request_uri_without_page(); ?>?cat="+dropdown.options[dropdown.selectedIndex].text.trim();
}
}