I'm working on a Quiz project. It needs modification constants in javascript files.
const questions=[
{
q:'where is the capital of India',
options:['New Delhi','Kolkatta','Varanashi','Agra'],
answer:1
},
{
q:'Who is the Prime Minister of India',
options:['Amit Shah','Narendra Modi','Rahul Gandhi','None of the above'],
answer:2
},
{
q:'where is the capital of India',
options:['New Delhi','Kolkatta','Varanashi','Agra'],
answer:1
}
]
But we need to add PHP on constant.
Try this, but not working...
const questions=[
{
q:'<?php echo the_field("q_1"); ?>',
options:['(<?php echo the_field("option_1"); ?>)','(<?php echo the_field("option_2"); ?>)','(<?php echo the_field("option_3"); ?>)','(<?php echo the_field("option_4"); ?>)'],
answer:'<?php echo the_field("answer_1"); ?>'
},
{
q:'<?php echo the_field("q_2"); ?>',
options:['<?php echo the_field("option_1_2"); ?>','<?php echo the_field("option_2_2"); ?>','<?php echo the_field("option_3_2"); ?>','<?php echo the_field("option_4_2"); ?>'],
answer:'<?php echo the_field("answer_2"); ?>'
},
{
q:'<?php echo the_field("q_3"); ?>',
options:['<?php echo the_field("option_1_3"); ?>','<?php echo the_field("option_2_3"); ?>','<?php echo the_field("option_3_3"); ?>','<?php echo the_field("option_4_3"); ?>'],
answer:'<?php echo the_field("answer_3"); ?>'
}
]
Here is the full code
If you print your JavaScript using PHP you could achieve the same result using the following code:
<?php
$questions = [
[
q => the_field("q_1"),
options => [
the_field("option_1"),
the_field("option_2"),
the_field("option_3"),
the_field("option_4")
],
answer => the_field("answer_1")
],
[
q => the_field("q_2"),
options => [
the_field("option_1_2"),
the_field("option_2_2"),
the_field("option_3_2"),
the_field("option_4_2")
],
answer => the_field("answer_2")
],
[
q => the_field("q_3"),
options => [
the_field("option_1_3"),
the_field("option_2_3"),
the_field("option_3_3"),
the_field("option_4_3")
],
answer => the_field("answer_3")
],
// ... more options here
];
$output = [];
foreach($questions as $question) {
$q = new stdClass();
$q->q = $question['q'];
$q->options = $question['options'];
$q->answer = $question['answer'];
array_push($output, $q);
}
and then, later in your HTML do something like that:
<script type="text/javascript">
const $questions = <?php echo json_encode($output); ?>;
console.log($questions);
</script>
Related
I'm trying to create a page with Woocommerce product category in tabs.
My tab menus are working, but i need to run a query in each tab content area to the corresponding category.
But when I click on each tab, the tab content shows all posts from the category not the belonging to the current tab. I didn't get the problem which is appearing, please can help me to solve the issue
Here is my code:
<?php
echo '<ul class="nav nav-tabs" role="tablist">';
$args = array(
'post_type' => 'product',
'posts_per_page' => 100,
'product_cat' => $category->slug,
'hide_empty'=> 1,
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_terms( 'product_cat', $args );;
foreach($categories as $category) {
echo '<li><a href="#' . $category->slug.'" role="tab" data-toggle="tab">' .
$category->slug.'('. $category->count .')</a></li>';
$cat_name = $category->slug;
}
echo '</ul>';
echo '<div class="tab-content">';
foreach($categories as $category) {
echo '<div class="tab-pane" id="' . $category->slug.'">';
?>
<?php
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) :
$loop->the_post();
?>
<h1><?php the_title(); ?></h1>
<?php
endwhile;
wp_reset_postdata();
?>
<?php
echo '</div>';
}
?>
The issue is that it displays all post of every category. I stuck on it..Please help
First, you have to get all categories and after that, you have to start a loop of categories and inside that loop get all products by category. check below code.
<?php
function load_scripts() {
wp_enqueue_style( 'jquery-ui-css', get_template_directory_uri().'/assets/css/jquery-ui.css', '' );
wp_enqueue_script( 'jquery-ui-js', get_template_directory_uri().'/assets/js/jquery-ui.js', array('jquery'), time() , false);
}
add_action('wp_enqueue_scripts', 'load_scripts');
function show_product_categories_tabs( $args ){
$atts = shortcode_atts( array(
'' => '',
), $atts, 'show_product_categories_tabs' );
ob_start();
?>
<div id="tabs">
<ul>
<?php
$categories = get_terms( array(
'taxonomy' => 'product_cat',
'hide_empty' => 1,
) );
foreach ( $categories as $key => $cat ) { ?>
<li><?php echo $cat->name; ?></li>
<?php } ?>
</ul>
<?php foreach ( $categories as $key => $cat ) {
$args = array(
'post_type' => 'product',
'posts_per_page' => 100,
'product_cat' => $cat->slug,
'hide_empty' => 1,
'orderby' => 'name',
'order' => 'ASC'
);
?>
<div id="<?php echo $cat->slug; ?>">
<?php
$products = new WP_Query( $args );
if( $products->have_posts() ) : while ( $products->have_posts() ) : $products->the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile; wp_reset_postdata(); endif; ?>
</div>
<?php } ?>
</div>
<script>
( function( $ ) {
$( "#tabs" ).tabs();
$("#tabs ul li").delegate('a', 'click', function(e){
e.preventDefault();
return false;
});
} )(jQuery);
</script>
<?php
$html = ob_get_clean();
return $html;
}
add_shortcode( 'show_product_categories_tabs', 'show_product_categories_tabs', 10, 1 );
?>
Tested and works.
Below is the code which generates the events for the fullcalendar
events: [
<?php $count=count($getBooking);$i=1;foreach($getBooking as $singleBooking){ ?>
{
title:'{{$singleBooking->roomLocation}}',
start:'{{$singleBooking->bookingDate}}T{{$singleBooking->bookingTime}}',
msg: 'Time: {{$singleBooking->bookingTime}} to {{$singleBooking->bookingTime+'03:00:00'}}:00:00<br>Course Name: {{$singleBooking->courseName}}<br>Room Name: {{$singleBooking->roomName}}<br>Service: {{$singleBooking->serviceName}}',
}
<?php if ($count > $i) { echo ',';}?><?php $i++; }?>
]
Posts can have multiple authors.
I want to add the possibility to delete authors in a post using Ajax.
PostsAuthorsTable.php
$this->belongsTo('Users', [
'className' => 'Users',
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
PostsTable.php
$this->hasMany('PostsAuthors', [ 'foreignKey' => 'post_id' ]);
PostsController.php
public function delete_author($authorID)
{
$id = $_GET['authorID'];
$this->Posts->PostsAuthors->delete($id);
$this->autoRender = false;
}
View: Posts > edit.ctp (JavaScript part)
<?php $this->start('script'); ?>
<script>
$(document).ready(function () {
$('.delete-author').on('click', function () {
$.ajax({
url: '<?= $this->Url->build(["action" => "delete_author"]) ?>',
type: 'GET',
data: { authorID: $(this).data('id') }
});
return false;
});
});
</script>
<?php $this->end(); ?>
View: Posts > edit.ctp (HTML part)
<?php foreach ($post_authors as $post_author): ?>
<tr>
<td><?= $post_author->user->name ?></td>
<td class="text-center">
<a href="#" class="delete-author text-danger" data-id="<?= $post_author->id ?>">
<i class="icon-trash"></i>
</a>
</td>
</tr>
<?php endforeach; ?>
Thank you for your help. :)
I found the solution.
PostsController.php
public function delete_author($authorID)
{
$id = $_GET['authorID'];
$entity = $this->Posts->PostsAuthors->get($id);
$this->Posts->PostsAuthors->delete($entity);
$this->autoRender = false;
}
I have implemented successfully the datatables server side processing on one of my tables just that the $('.select_users').change(function(event){ doesn't work anymore on my select tab, despite the fact it shows correctly. When I try to select an option from the select tag it should action to the jquery function but it doesn't.
EDIT 28 NOV 2014
I have found that there is an issue with the events and server side processing:
http://www.datatables.net/examples/advanced_init/events_live.html.
So how can I convert script BLOCK #1 to match the script from the above link.
I added the
$('#dataTables-ss').on('click', 'tr', function () {
var name = $('td', this).eq(0).text();
alert( 'You clicked on '+name+'\'s row' );
} );
And this was getting triggered.
BLOCK #1 => Jquery - on change of select it should trigger this function
$('.select_users').change(function(event){
var selected_value = this.value;
var id = $(this).find('option:selected').attr('class');
var id = id.split('-');
var select_id = id[1];
$.ajax({
type: 'post',
url: 'includes/ajax.html',
data: {
action: 'confirm_notconfirm_subscribers',
selected_value: selected_value,
select_id: select_id
},
success: function(data) {
$('#message').html(data).fadeIn(1000).fadeOut(1000);
},
error: function() {
$("#result").html('There was an error');
}
});
});
BLOCK #2 => PHP important part
public function read_subscriber_table() {
$table = 'subscribers';
$primaryKey = 'ID';
$columns = array(
array( 'db' => 'name', 'dt' => 1 ),
array( 'db' => 'email', 'dt' => 2 ),
array( // issue is here in the third array where I create the select string.
'db' => 'confirmed',
'dt' => 3,
'formatter' => function( $d, $row ) {
if ($d == '1') {
$confirmed = 'Confirmed';
} else {
$confirmed = 'Not Confirmed';
}
if ($d !== '1') { $selected = 'selected'; } else { $selected = ''; }
$string = '<select class="select_users form-control" name="status-users">
<option class="opt-'.$row["ID"].'" value="1" '.$selected.'>Confirmed</option>
<option class="opt-'.$row["ID"].'" value="0" '.$selected.'>Not Confirmed</option>
</select>';
return $string;
}
),
array(
'db' => 'date',
'dt' => 4,
'formatter' => function( $d, $row ) {
return date( 'd-m-Y', strtotime($d));
}
),
array(
'db' => 'ID',
'dt' => 5,
'formatter' => function( $d, $row ) {
return '<input type="checkbox" class="checkbox_subscribers" value="'.$d.'" >';
}
)
);
$sql_details = $this->dtss_processing();
require( 'ssp.class.php' );
$result = SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns );
$start=$_REQUEST['start'] + 1;
foreach($result['data'] as &$res){
$res[0]=(string)$start;
$start++;
}
echo json_encode($result);
}
BLOCK #3 => Datatables initialized script
$(document).ready(function() {
$('#dataTables-ss').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "includes/data_tables.html?action=read_subscriber_table",
"aaSorting": [[4, 'desc']]
} );
} );
BLOCK #4 => EDIT - before implementing server side the function was looking like this and it was working well.
public function read_subscriber_table() {
$col_names = array('ID', 'name', 'email', 'confirmed', 'date');
$this->read_table('subscribers', $col_names);
$i = 0;
foreach ($this->results as $item) {
$i++;
if ($item->confirmed == '1') {
$confirmed = 'Confirmed';
} else {
$confirmed = 'Not Confirmed';
}
if ($item->confirmed !== '1') { $selected = 'selected'; } else { $selected = ''; }
?>
<tr id="tablerow-<?php echo $item->ID; ?>">
<td><?php echo $i; ?></td>
<td><?php echo $item->name; ?></td>
<td><?php echo $item->email; ?></td>
<td>
<select class="select_users form-control" name="status-users">
<option class="opt-<?php echo $item->ID; ?>" value="1" <?php echo $selected ?>>Confirmed</option>
<option class="opt-<?php echo $item->ID; ?>" value="0" <?php echo $selected ?>>Not Confirmed</option>
</select>
</td>
<td><?php echo $item->date; ?></td>
<td><input type="checkbox" class="checkbox_subscribers" value="<?php echo $item->ID; ?>" ></td>
</tr>
<?php
}
?>
<?php
}
Follwing on from comments...
Using that updated code as a starting point, change $('#dataTables-ss').on('click', 'tr', function () { to $('#dataTables-ss').on('change', '.select_users', function(event){
i currently have a wordpress with a custom post type and a custom taxonomy attached to this. ( jobs_category ).
I have the build listing out the categories from this taxonomy like so:
<?php
$taxonomy = 'jobs_category';
$tax_terms = get_terms($taxonomy);
?>
<ul>
<?php
foreach ($tax_terms as $tax_term) {?>
<li id="cat-<?php echo $tax_term->term_id; ?>">
<?php echo $tax_term->name; ?>
</li>
<? } ?>
</ul>
I have then used the following in my functions file:
add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
$cat_id = $_POST[ 'cat' ];
$args = array (
'cat' => $cat_id,
'posts_per_page' => 10,
'order' => 'DESC'
);
$posts = get_posts( $args );
ob_start ();
foreach ( $posts as $p ) { ?>
<div id="post-<?php echo $post->ID; ?>">
<h1 class="posttitle"><?php the_title(); ?></h1>
<div id="post-content">
<?php the_excerpt(); ?>
</div>
</div>
<?php } wp_reset_postdata();
$response = ob_get_contents();
ob_end_clean();
echo $response;
die(1);
}
To do the AJAX with the following JS:
<script>
function cat_ajax_get(catID) {
jQuery("a.ajax").removeClass("current");
jQuery("a.ajax").addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
jQuery("#loading-animation-2").show();
var ajaxurl = '/wp-admin/admin-ajax.php';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "load-filter", cat: catID },
success: function(response) {
jQuery("#category-post-content").html(response);
jQuery("#loading-animation").hide();
return false;
}
});
}
</script>
My question is how do i get it to use the custom taxonomy categories? Im not 100% sure because i've never done it before.
Any help would be great.
Thanks
You have to use tax_query instead of cat. While category is used for native Wordpress taxonomy, so it won't work for custom taxonomies.
Replace your array $args to this:
$args = array (
'tax_query' => array(
array(
'taxonomy' => 'jobs_category',
'field' => 'term_id',
'terms' => array( $cat_id )
)
),
'post_type' => 'jobs', // <== this was missing
'posts_per_page' => 10,
'order' => 'DESC'
);