Pass single PHP value from ACF Repeater Field - javascript

I have a page for team members of a company. The team members are rendered with an ACF repeater that has fields for Name, Job Title, and Biography. On the page I would like to render just their Name, and Job Title. If you were to click on a team member, that would open a modal that would render that team members biography.
I have this working, but my approach adds the Biography field to the DOM for each team member, hides it, and passes it into the modal on click. I am wondering if it is possible to pass the Biography field into the modal without having to render the text in the DOM initially and hiding it?
Below is my current code:
<!-- acf repeater -->
<?php if( have_rows('team_member') ): ?>
<?php while( have_rows('team_member') ): the_row();
$name = get_sub_field('name');
$job_title = get_sub_field('job_title');
$biography = get_sub_field('biography');
?>
<div class="team-member">
<div>
<?php echo $name ?>
</div>
<div>
<?php echo $job_title ?>
</div>
<div class="biography" style="display: none;">
<?php echo $biography ?>
</div>
</div>
<?php endwhile; ?>
<!-- modal -->
<div class="modal">
modal
<div class="modal-biography">
</div>
</div>
<?php endif; ?>
<!-- javascript -->
jQuery(function($) {
$('.team-member').on('click', function() {
var modalBiography = $(this).find('.biography').text();
$('.modal-biography').text(modalBiography);
})
});

If you don't need to display the bio div, I'd suggest just putting it into a data-bio attribute:
<div class="team-member" data-bio="<?php echo $biography; ?>">
<div><?php echo $name; ?></div>
<div><?php echo $job_title; ?></div>
</div>
then tweak js a bit to pull this data-bio instead:
jQuery(function($) {
$('.team-member').on('click', function() {
var modalBiography = $(this).data('bio');
$('.modal-biography').text(modalBiography);
})
});

Related

Wordpress - Show random post with JS, not PHP

I have this page containing recent posts at the bottom. I have set it to randomly show me three posts from the same category as the current post. Heres the loop:
<!-- Related Posts =========================================== -->
<div class="relared-posts-heading">
<h2>SIMILAR INSIGHTS</h2>
</div>
<div class="container blog-card-container">
<div class="card-columns">
<?php
// the query
$the_query = new WP_Query( array(
'orderby' => 'rand',
'cat' => '-14',
'posts_per_page' => 3,
));
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<!-- Conditional a Link =========================================== -->
<?php
if(get_field('quote') == ''){
$yourTag = "<a href='".get_the_permalink()."'>" ;
} else {
$yourTag = "";
}
?>
<div> <?php echo $yourTag; ?> </div>
<div class="card">
<a href="<?php the_permalink(); ?>">
<div class="blog-thumb-container-2">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?>
</div>
</a>
<div class="blog-meta-container-2">
<p class="blog-cat-label"><?php the_category(', '); ?></p>
<h2 class="blog-card-title"><?php the_title(); ?></h2>
<p class="card-text"><?php the_excerpt(__('(more…)')); ?></p>
<p><strong><?php the_author(); ?></strong> | <?php echo get_the_date(); ?> </p>
</div>
</div>
</a>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php __('No News'); ?></p>
<?php endif; ?>
</div>
</div>
This works fine currently.
The trouble is, when finished, the site will be behind a clients custom cache and he tells me that PHP randomisers wont work as it will just show the cached version. He suggested I do any randomising using Javascript!
So firstly - is this possible? Secondly, How would I go about targeting this is javascript!? Thanks for looking!!
Unfortunately you won't be able to randomize a post in this way for the caching reason.
What you can do instead is use an Ajax call to dynamically fetch and insert a random post...
$.get('/wp-content/themes/SomeTheme/random.php?v=' + Math.floor(Date.now() / 1000))
.done(function(resp) {
$('.random-post').html(resp);
})
.fail(function(xhr) {
// handle error (xhr object contains the response)
});
And then create a separate random.php file in your theme and put the code to randomly return a single post in there. Note, that you don't need to put the whole layout around the post (don't include header.php etc). That's because this exact HTML fragment will be sent to the frontend and inserted dynamically.
The ?v= parameter is required for cache busting so that it fetches a new post each time.
Try wrapping the entire funtionality as a shortcode.

Adding a second custom field

I have a custom field 'ExtraCSS' which brings in custom post css using the following code. (It is brought in from a 'have_posts()' loop)
html
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?><!-- get specific css for post -->
<article>
<div id="post-<?php the_ID(); ?>" class="img-cell" style="background-image:url('<?php echo $thumbnail_url ?>');" <?php post_class('col-md-12'); ?> >
<a class="linkage" href="<?php the_permalink(); ?>"</a>
</div><!-- /#post -->
<div class="text-cell">
<div class="<?php echo $extraCSS?>" >
<h1><?php the_title(); ?></h1>
<h3><?php the_category(', '); ?></h3>
</div>
</div>
</article>
*EDIT
I want to add 1 more custom field ('BG-align') with either values 'BG-align-L' or 'BG-align-R'. I figured I just add another similar line of code under the current one.
ex.
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?>
<?php $BGalign = get_post_meta(get_the_ID(),'BGalign',true);?>
but it doesn't work
According to *edit:
'BGalign' have to be defined in post (by "Add New Custom Field"), otherwise it is just empty.
You could set default value (edit "default-value") if not set in post:
<?php
$BGalign = get_post_meta(get_the_ID(),'BGalign',true);
$BGalign = ( !empty($BGalign) ? $BGalign : "default-value" );
?>
Then remember to echo that new php variable. For example:
<div class="<?php echo $extraCSS . " " . $BGalign; ?>" >
. is dot joining variables into one string
" " is empty space for sure that your both classes names will not be connected

Drupal/Jquery: hide parent div if child is empty

I am having difficulty working this out. What I wish to achieve is when works-left and works-right are empty (keeping in mind it functions using drupal pre-processed code) the parent div (latest-works-container) will disappear.
I was wondering if there were somesort of solution to the problem. The thing that came to me was editing the template.php code that is found in bartik, or some other possible solution?
function hybrid_preprocess_html(&$variables) {
if (!empty($variables['page']['featured'])) {
$variables['classes_array'][] = 'featured';
}
if (!empty($variables['page']['services_first'])
|| !empty($variables['page']['services_second'])
|| !empty($variables['page']['services_third'])
|| !empty($variables['page']['services_fourth'])) {
$variables['classes_array'][] = 'services';
}
<div id="latest-works-container"><!--latest-works-container-->
<div id="latest-works"><!--latest-works-->
<div class="works-left">
<?php print render($page['portfolio_works_first']); ?>
</div>
<div class="works-right">
<?php print render($page['portfolio_works_second']); ?>
</div>
<div class="works-left">
<?php print render($page['portfolio_works_third']); ?>
</div>
<div class="works-right">
<?php print render($page['portfolio_works_fourth']); ?>
</div>
</div><!--/latest-works-->
</div><!--/latest-works-container-->
Your element content comes from PHP, so you have no need to remove div using jQuery.
Instead, you should edit your view file. So for example you have you render() method, which gives your the content of div.
$contentBlockFirstLeft = render($page['portfolio_works_first']);
$contentBlockSecondLeft = render($page['portfolio_works_third']);
$contentBlockFirstRight = render($page['portfolio_works_second']);
$contentBlockSecondRight = render($page['portfolio_works_fourth']);
$isLeftBlockEmpty = empty($contentBlockFirstLeft) && empty($contentBlockSecondLeft);
$isRightBlockEmpty = empty($contentBlockFirstRight) && empty($contentBlockSecondRight);
$showAllBlocks = true;
if ($isLeftBlockEmpty && $isRightBlockEmpty) {
$showAllBlocks = false;
}
So you already know all needed information to output your elemnt, so for example you will have next view. Please feel free to change variable names according to business logic needed, those are just dummy names.
<?php if ($showAllBlocks): ?>
<div id="latest-works-container"><!--latest-works-container-->
<div id="latest-works"><!--latest-works-->
<div class="works-left">
<?php echo $contentBlockFirstLeft; ?>
</div>
<div class="works-right">
<?php echo $contentBlockFirstRight; ?>
</div>
<div class="works-left">
<?php echo $contentBlockSecondLeft; ?>
</div>
<div class="works-right">
<?php echo $contentBlockSecondRight; ?>
</div>
</div><!--/latest-works-->
</div><!--/latest-works-container-->
<?php endif; ?>

Dynamic jQuery with same ID

Im trying to make a dynamic jQuery function with some help from Advanced Custom Fields in Wordpress. This may not have something to do with the question, but I work in Wordpress with this plugin, anyway.
My code is like this:
<div id="restaurangmeny">
<h2>Vår meny</h2>
<? if( get_field('meny_for_restaurangen') ): ?>
<?php while( has_sub_field('meny_for_restaurangen') ): ?>
<div class="kategori">
<div class="kategorinamn" id="<?php the_sub_field('namn_for_kategorin'); ?>"><?php the_sub_field('namn_for_kategorin'); ?></div>
<div class="matratter" id="<?php the_sub_field('namn_for_kategorin'); ?>">
<? if( get_sub_field('matratter') ): ?>
<?php while( has_sub_field('matratter') ): ?>
<div class="matratt">
<div class="left">
<div class="namn"><?php the_sub_field('namn_pa_matratt'); ?></div>
<div class="beskrivning"><?php the_sub_field('beskrivning_av_matratten'); ?></div>
</div>
<div class="pris"><?php the_sub_field('pris_pa_matratten'); ?>:-</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div><!--#restaurangmeny-->
So what I want is when I click on the div called "kategorinamn" I want to div called "matratter" be shown or hidden. That's why I use same id for "kategorinamn" and "matratter" just because these 2 belong together.
Simply, if I click on 1 I want everything that got the same id (1) be shown. If I click on 2 I want everything that got the same id (2) be shown.
I don't know what dynamic jQuery like this is called, but I'm far away from being good with jQuery so that's why I'm asking.
Something like this http://jsfiddle.net/gwK6d/18/, but with jQuery only and that fit's my code above.
1) Import jquery
2) Make sure you are not using the same id for multiple elements
3) Change this bit:
<div class="kategorinamn" id="<?php the_sub_field('namn_for_kategorin'); ?>"><?php the_sub_field('namn_for_kategorin'); ?></div>
<div class="matratter" id="<?php the_sub_field('namn_for_kategorin'); ?>">
To this:
<div class="kategorinamn" id="<?php the_sub_field('namn_for_kategorin'); ?>">
<?php the_sub_field('namn_for_kategorin'); ?>
<div class="matratter" id="<?php the_sub_field('namn_for_kategorin'); ?>">
</div>
4) Declare this function after load:
$(".kategorinamn").click(function(){
$(this).children('.matratter').toggle();
});
JSFIDDLE: http://jsfiddle.net/uRpc8/

Div loaded through Ajax no longer works with JavaScript

I am using CakePHP for an application where I am trying to add some Ajax functionality to update in page content.
JavaScript libraries: Prototype, Scriptaculous, jQuery, jEditable
By default: Load 5 rows and option to load 10 more rows on the page
Editable options: clicking on a field will use the jEditable to allow users to edit the fields and save.
Current situation: When the page loads for the first time, all functionalities work, but when I load 10 more rows, the JavaScript functions stop working.
Here is the index view file which calls an element containing all the entries with the JavaScript functions:
<div id="latestResults" class="wrap">
<?php
echo $this->element('current_entries', array('entries' => $entries));
?>
</div>
<script type="text/javascript">
var clientsInput= <?php echo json_encode($clients); ?>;
$j('.client').editable("<?php echo $this->Html->url(array('controller'=>'entries', 'action'=>'editEntryClient')); ?>/", {
data : clientsInput,
name : 'data[Entry][client_id]',
type : 'select',
onblur : 'submit'
});
//Inline editor for projects
var projectsInput= <?php echo json_encode($projects); ?>;
$j('.project').editable("<?php echo $this->Html->url(array('controller'=>'entries', 'action'=>'editEntryProject')); ?>/", {
data : projectsInput,
name : 'data[Entry][project_id]',
type : 'select',
onblur : 'submit'
});
//Inline editor for tasks
var tasksInput= <?php echo json_encode($tasks); ?>;
$j('.task').editable("<?php echo $this->Html->url(array('controller'=>'entries', 'action'=>'editEntryTask')); ?>/", {
data : tasksInput,
name : 'data[Entry][task_id]',
type : 'select',
onblur : 'submit'
});
//Inline editor for hours spent
$j('.hours_spent').editable("<?php echo $this->Html->url(array('controller'=>'entries', 'action'=>'editEntryHoursSpent')); ?>/", {
name : 'data[Entry][hours_spent]',
onblur : 'submit'
});
//Inline editor for notes
$j('.notesCol').editable("<?php echo $this->Html->url(array('controller'=>'entries', 'action'=>'editEntryDescription')); ?>/", {
name : 'data[Entry][description]',
onblur : 'submit'
});
//Load more
$j('#load_more').click(function(){
//Get last id
var currentNumberOfRows = $j('.row').length;
var newNumberOfRowsToDisplay =currentNumberOfRows + 10;
var urlToGet = "<?php echo $this->Html->url(array('controller'=> 'entries', 'action'=>'displayCurrentEntries')); ?>/" + newNumberOfRowsToDisplay;
$j.get(urlToGet, function(data){
$j('#latestResults').html(data);
});
});
<?php echo $this->Html->script('inpage', array('inline'=>true)); ?>
current_entries.ctp
<?php
$i = 0;
foreach ($entries as $entry):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
$div_id = null;
$div_id = "id='entry_".$entry['Entry']['id']."'";
$row_id = "id='row_".$entry['Entry']['id']."'";
?>
<!-- ROW 1 -->
<div class="row">
<!-- clients -->
<div class="clientCol">
<div class='client result' id='client_<?php echo $entry['Entry']['id']; ?>'><?php echo $entry['Client']['name']; ?></div>
</div>
<!-- projects -->
<div class="projectCol">
<div class='project result' id='project_<?php echo $entry['Entry']['id']; ?>'><?php echo $entry['Project']['name']; ?> </div>
</div>
<!-- tasks -->
<div class="taskCol">
<div class='task result' id='task_<?php echo $entry['Entry']['id']; ?>'><?php echo $entry['Task']['name']; ?> </div>
</div>
<!-- hours -->
<div class="hoursCol">
<div class='hours_spent result' id='hours_spent_<?php echo $entry['Entry']['id']; ?>'><?php echo $entry['Entry']['hours_spent']; ?> </div>
</div>
<!-- Date -->
<div class="dateCol">
<?php echo $entry['Entry']['date_of_task']; ?>
</div>
<!-- notes -->
<div class="notesCol" id='description_<?php echo $entry['Entry']['id']; ?>'>
<?php echo $entry['Entry']['description']; ?>
</div>
<!-- submit -->
<div class="submitCol">
<div class="options">
<a class="duplicate" href=""></a>
<?php echo $ajax->link('', array('controller'=>'entries', 'action' => 'delete', $entry['Entry']['id']), array('class'=>'remove', 'update'=>'latestResults'), 'Are you sure you want to delete this?'); ?>
</div>
</div>
<div class="clear"> </div>
</div>
<?php endforeach; ?>
<!-- //ROW 1 -->
<!-- Load Row -->
<div class="row load">
Load 10 more rows
</div>
<!-- // Load Row -->
When the page loads, all the $j('div.class').editable('') functions work. But whenever it is loading more rows, all these functions stop working alltogether. I might be missing something really simple here, but any help or guidance on this would be brilliant. Note that the loadmore only updates the #latestResults in page through the Ajax call.
Thanks a million in advance.
Regards
Tas

Categories