In an archive page I have a list of X posts and each post has a thumbnail that is being displayed in a lightbox slideshow.
What i'm trying, is to get the permalink for each post item within a loop, and to print it in a script function that is outside of the loop.
This is the loop for the archive page.
<?php
if ( get_query_var('paged') ) $paged = get_query_var('paged');
if ( get_query_var('page') ) $paged = get_query_var('page');
$query = new WP_Query( array( 'post_type' => 'gallery', 'paged' => $paged, 'orderby' => 'rand' ) );
if ( $query->have_posts() ) : ?>
<div class="work-info">
<a rel="<?php the_permalink();?>" href="<?php echo $imageF[0]; ?>" class="lightbox" data-title="<?php the_title();?>" ></a>
</div>
<?php endwhile; wp_reset_postdata(); ?>
<?php endif; ?>
and on the same php file, just outside the loop...
<script>
jQuery(document).ready(function($){
$('.lightbox').iLightBox(
{
skin: 'smooth',
path: 'horizontal',
linkId: 'showcase',
social: {
buttons: {
facebook: {
URL: "<?php echo get_permalink();?>",
text: "Share it on your Timeline"
},
}
},
}
);
});
</script>
As you see, the URL: "" will only display 1 random permalink from the post list, because is outside the loop.
What i want is to have a URL:" " for each of the posts with their own permalink.
Thanks for your time!
UPDATE
After taking a look at the plugin's code, I suggest to try a different approach. This should work even for image galleries.
You can use the data-options attribute to set the sharing url of each .lightbox item.
Try this:
<a rel="<?php the_permalink();?>" href="<?php echo $imageF[0]; ?>" class="lightbox" data-title="<?php the_title();?>" data-options="social: { facebook: { URL: '<?php the_permalink(); ?>', text:'Share this photo on Facebook' }, twitter: { URL: '<?php the_permalink(); ?>', text:'Share this photo on Twitter' } }" ></a>
And your javascript code should be:
<script>
jQuery(document).ready(function($){
$('.lightbox').iLightBox({
skin: 'smooth',
path: 'horizontal',
linkId: 'showcase'
});
});
</script>
As I see from your code, each .lightbox element has a rel attribute with the post permalink. So I suggest to loop through each element with the class .lightbox (using jQuery .each() method) and add the iLightBox function for each of them. Try the following code:
jQuery(document).ready(function($){
$('.lightbox').each(function() {
$(this).iLightBox({
skin: 'smooth',
path: 'horizontal',
linkId: 'showcase',
social: {
buttons: {
facebook: {
URL: $(this).attr("rel"),
text: "Share it on your Timeline"
}
}
}
});
});
});
Let me know if it works.
More info about jQuery .each() method here.
Not quite sure what you are trying to do with your script, but the way to go would be to build an array of permalinks as the loop runs
Before your loop begins make a
$permalink_array = array();
Then within the link for each post
$permalink_array[] = get_the_permalink();
When you want to print all your permalinks use something like
foreach( $permalink_array as $permalink ) {
echo $permalink;
}
Related
I am building a news blog that upload posts every hour. I have created a shortcode that displays the last 15 posts on the home page. My problem was that the server cache needed to be deleted every hour. so I've decided to serve the post via AJAX so this area will get the latest posts every page load.
I found this answer and combine it whit my code.
My problem is that it displays all of the posts and not just 15.
PHP:
function get_ajax_posts() {
// Query Arguments
$args = array(
'post_type' => array('post'),
'post_status' => array('publish'),
'posts_per_page' => 15,
'nopaging' => true,
'order' => 'DESC',
'orderby' => 'date',
);
$ajaxposts = new WP_Query( $args );
$response = '';
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part( 'template-parts/content-archive');
}
} else {
$response .= get_template_part('none');
}
echo $response;
exit; // leave ajax call
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
JS:
$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "html",
data: { action : 'get_ajax_posts' },
success: function( response ) {
$( '.home-hot-flights' ).html( response );
//hot-flights
var hot_flights_item = $(".home-hot-flights article").width() + 17;
$(".art-move-left").click(function () {
$('.move-right').addClass('show-move-right');
var leftPos = $('.home-hot-flights').scrollLeft();
$(".home-hot-flights").animate({scrollLeft: leftPos - hot_flights_item}, 200);
});
$(".art-move-right").click(function () {
var leftPos = $('.home-hot-flights').scrollLeft();
$(".home-hot-flights").animate({scrollLeft: leftPos + hot_flights_item}, 200);
});
}
});
This might help you:
Pagination parameters
(nopaging (boolean) – show all posts or use pagination. Default value
is ‘false’, use paging. )
Display all posts by disabling pagination:
$query = new WP_Query( array( 'nopaging' => true ) );
I think you should remove that parameter if you want to display a certain number of posts using posts_per_page.
Try this piece of code I have edit your code please see below
function get_ajax_posts() {
// Query Arguments
$args = array(
'post_type' => array('post'),
'post_status' => array('publish'),
'posts_per_page' => 15,
'order' => 'DESC',
'orderby' => 'date',
);
wp_reset_query();
$ajaxposts = new WP_Query( $args );
$response = '';
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part( 'template-parts/content-archive');
}
} else {
$response .= get_template_part('none');
}
echo $response;
exit; // leave ajax call
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
If the two loops data is overwridden then, I your first code wp_reset_query() is incorrect. If you are using WP_Query then
wp_reset_postdata() //remove wp_reset_query() which is used for wp_query()
should be used after the end of the WHILE loop which means that in your two loops you have to have
wp_reset_postdata() // use this at both loops
I want to use a php for loop to create some file inputs with FilePond.
Each instance needs to have its own unique url, and use the plugins initiated. I have got the actual file uploads working, although the plugins don't seem to be getting used.
<?php
foreach ($objArray as $value) {
$inputNumber2++;
?>
<input name="input_<?= $inputNumber2; ?>_images[]" id="input_<?= $inputNumber2; ?>_images" class="filepond" type="files" multiple />
<script>
document.addEventListener('DOMContentLoaded', function() {
window['input<?= $inputNumber2; ?>Images'] = FilePond.create(
document.querySelector('#input_<?= $inputNumber2; ?>_images'),
{
server: {
url: '<?= Config::get('URL'); ?>',
process: 'upload/images/input_<?= $inputNumber2; ?>_images',
revert: 'upload/revert',
load: 'files/',
},
<?php
if (isset($value->imageArray) && count($value->imageArray) > 0) {
echo 'files: [';
foreach ($value->imageArray as $imageName) {
echo '{
source: "'.$imageName.'",
options: {
type: "local",
file: {
name: "'.$imageName.'",
type: "image/jpeg"
}
}
},';
}
echo '],';
}
?>
}
);
});
</script>
<?php } ?>
...
<script>
document.addEventListener('DOMContentLoaded', function() {
FilePond.registerPlugin(
FilePondPluginFileValidateType,
FilePondPluginImageExifOrientation,
FilePondPluginImagePreview,
FilePondPluginImageTransform,
FilePondPluginImageCrop,
FilePondPluginImageResize
);
FilePond.setOptions({
acceptedFileTypes: ['image/*'],
labelIdle: 'Add images or <span class="filepond--label-action"> Browse </span>',
imagePreviewMaxHeight: 100,
imagePreviewZoomFactor: 1,
});
});
</script>
I'm probably doing it wrong - how should I be doing it?
Also, it is picking up and using the custom label so some settings it is getting.
This line:
document.querySelector('#input_<?= $inputNumber2; ?>_images')
Returns a field with the id input_<?= $inputNumber2; ?>_images. But you've only assigned the name attribute to your input field. I suspect adding the id attribute to the input will solve the issue.
OR you can change the selector to:
document.querySelector('input[name="input_<?= $inputNumber2; ?>_images"]')
I am making a WordPress Plugin that adds an option to add a custom gift voucher to the checkout page. I have managed to get the gift voucher inputs and "apply now" button working and it adds the voucher value to the checkout totals, and it adjusts the total accordingly.
The problem is that my plugin seems to cause the "Place order" button to not be clickable. When I deactivate the plugin the checkout button works fine, so there is something in the plugin code that is causing the conflict. I've checked in the browser console and there are no errors being displayed for this page. Here is the code so far:
function my_init() {
if (!is_admin()) {
// comment out the next two lines to load the local copy of jQuery
wp_deregister_script('jquery');
wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', false, '1.3.2');
wp_enqueue_script('jquery');
}
}
function giftvoucher_front_end_scripts() {
wp_enqueue_script( 'my_custom_script', plugin_dir_url( __FILE__ ) . 'js/gift_voucher.js' , array( 'jquery' ), '', true );
}
add_action( 'wp_enqueue_scripts', 'giftvoucher_front_end_scripts' );
// Displaying a select field and a submit button in checkout page
function gift_voucher_value_check() {
echo '<a class="button alt" name="gift_voucher_action_btn" id="gift_voucher_action" value="Apply" data-value="gift_voucher_data_value">Apply Now</a>';
}
add_action( 'woocommerce_checkout_after_customer_details', 'gift_voucher_value_check', 10, 0 );
// jQuery - Ajax script
function gift_voucher_redeem_script() {
// Only checkout page
if ( ! is_checkout() ) return;
?>
<script type="text/javascript">
jQuery( function($){
$('#gift_voucher_action').on('click', function() {
redeemvoucher();
$.ajax({
type: "post",
url: wc_checkout_params.ajax_url,
data: {
'action' : 'gift_voucher_redeem',
//'gift_voucher_value' : $("#rx-redemption-points").val()
'gift_voucher_value' : $("#gift_voucher_redeem").val()
},
success: function(response) {
$('body').trigger('update_checkout');
console.log('response: '+response); // just for testing | TO BE REMOVED
},
error: function(error){
console.log('error: '+error); // just for testing | TO BE REMOVED
}
});
})
}
</script>
<?php
}
add_action( 'wp_footer', 'gift_voucher_redeem_script' );
// Wordpress Ajax code (set ajax data in Woocommerce session)
add_action( 'wp_ajax_gift_voucher_redeem', 'gift_voucher_redeem' );
add_action( 'wp_ajax_nopriv_gift_voucher_redeem', 'gift_voucher_redeem' );
function gift_voucher_redeem() {
if( isset($_POST['gift_voucher_value']) ){
WC()->session->set( 'custom_fee', esc_attr( $_POST['gift_voucher_value'] ) );
echo true;
}
exit();
}
add_action( 'wp_ajax_gift_voucher_redeem', 'gift_voucher_redeem' );
add_action( 'wp_ajax_nopriv_gift_voucher_redeem', 'gift_voucher_redeem' );
// Add a custom dynamic discount based on gift_voucher_data_value
function gift_voucher_value_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only for targeted shipping method
if ( WC()->session->__isset( 'custom_fee' ) )
$discount = (float) WC()->session->get( 'custom_fee' );
if( isset($discount) && $discount > 0 )
$cart->add_fee( __( 'Giftvoucher discount', 'woocommerce' ), -$discount );
}
add_action( 'woocommerce_cart_calculate_fees', 'gift_voucher_value_discount', 20, 1 );
// Add the gift voucher fields to the checkout page
function customise_checkout_field($checkout)
{
echo '<div id="customise_checkout_field"><h3>' . __('Have a Giftvoucher?') . '</h3>';
echo '<form>';
woocommerce_form_field('voucher_number_field', array(
'type' => 'text',
'class' => array(
'my-field-class form-row-wide'
) ,
'label' => __('Enter your giftvoucher number') ,
'id' => 'gift_voucher_number',
'placeholder' => __('19 digits, no spaces') ,
'required' => true,
) , $checkout->get_value('voucher_number_field'));
woocommerce_form_field('pin_field', array(
'type' => 'text',
'class' => array(
'my-field-class form-row-wide'
) ,
'id' => 'gift_voucher_pin',
'label' => __('Enter your PIN') ,
'placeholder' => __('4 digits') ,
'required' => true,
) , $checkout->get_value('pin_field'));
woocommerce_form_field('redeem_amount_field', array(
'type' => 'text',
'class' => array(
'my-field-class form-row-wide'
) ,
'label' => __('Amount to redeem $') ,
'id' => 'gift_voucher_redeem',
'placeholder' => __('0.00') ,
'required' => true,
) , $checkout->get_value('redeem_amount_field'));
//echo '<input type="button" value="Redeem Giftvoucher" onclick="redeemvoucher()"';
echo '<span id="redeemed"></span>';
echo '</form>';
echo '</div>';
}
add_action('woocommerce_after_order_notes', 'customise_checkout_field');
Can anyone assist me in finding what is causing this conflict with the "Place order" button? Thanks in advance.
Well it turns out that the answer was that the "Apply now" button was actually outside of the form tags... which is okay, I can live with that... but when I commented out the form tags, the checkout works perfectly when clicking the "Place order" button.
Must give credit to a colleague who had a look at the code and pointed out the issue to me... Thanks James!
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 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'
);