Wordpress Advanced Custom Fields - Cleaner Way To Code This - php

I have added advanced custom fields to woocommerce category pages to help with SEO.
Is there a cleaner way to code this as a lot of excess probably don't need
<div class="full top-cat-seo">
<?php
$queriedObject=get_queried_object();
echo get_field('product_category_top_section_seo','product_cat_'.$queriedObject->term_id);
$link1 = get_field('link_url_1','product_cat_'.$queriedObject->term_id);
$link1name = get_field('link_url_1_name','product_cat_'.$queriedObject->term_id);
$link2 = get_field('link_url_2','product_cat_'.$queriedObject->term_id);
$link2name = get_field('link_url_2_name','product_cat_'.$queriedObject->term_id);
$link3 = get_field('link_url_3','product_cat_'.$queriedObject->term_id);
$link3name = get_field('link_url_3_name','product_cat_'.$queriedObject->term_id);
$link4 = get_field('link_url_4','product_cat_'.$queriedObject->term_id);
$link4name = get_field('link_url_4_name','product_cat_'.$queriedObject->term_id);
if( $link1 ): ?>
<a class="button" href="<?php echo esc_url( $link1 ); ?>"><?php echo esc_html( $link1name );?></a>
<?php endif; ?>
<?php if( $link2 ): ?>
<a class="button" href="<?php echo esc_url( $link2 ); ?>"><?php echo esc_html( $link2name );?></a>
<?php endif; ?>
<?php if( $link3 ): ?>
<a class="button" href="<?php echo esc_url( $link3 ); ?>"><?php echo esc_html( $link3name );?></a>
<?php endif; ?>
<?php if( $link4 ): ?>
<a class="button" href="<?php echo esc_url( $link4 ); ?>"><?php echo esc_html( $link4name );?></a>
<?php endif; ?>
</div>
there are 8 custom fields to create 4 buttons as per here
https://onepoundcrisps.com/cat/brand/kp/

Using a loop, you build the name of the field from the loop key. So instead of hardcoding link_url_1, you can use 'link_url_' . $i where $i is the loop index.
You can also fetch the link and only fetch the linkname if there is a value.
This means you do 1 set of code and any changes will be reflected on all elements...
$queriedObject = get_queried_object();
echo get_field('product_category_top_section_seo', 'product_cat_' . $queriedObject->term_id);
for ($i = 1; $i < 5; $i++) {
$link = get_field('link_url_' . $i, 'product_cat_' . $queriedObject->term_id);
if ($link) {
$linkName = get_field('link_url_' . $i . '_name', 'product_cat_' . $queriedObject->term_id);
echo '<a class="button" href="' . esc_url($link) . '">' . esc_html($linkName) . '</a>';
}
}
I've converted the HTML to an echo, if you feel more comfortable with your current version, you should just need to change the field names (just remove the number).

Instead of using a separate conditional statement for each link, you can use a loop to iterate over all the links and display them. Here's how it can be done:
<div class="full top-cat-seo">
<?php
$queriedObject = get_queried_object();
echo get_field('product_category_top_section_seo', 'product_cat_' . $queriedObject->term_id);
?>
<?php
for ($i = 1; $i <= 4; $i++) {
$link = get_field("link_url_{$i}", "product_cat_{$queriedObject->term_id}");
$linkname = get_field("link_url_{$i}_name", "product_cat_{$queriedObject->term_id}");
if ($link) {
?>
<a class="button" href="<?php echo esc_url($link); ?>"><?php echo esc_html($linkname); ?></a>
<?php
}
}
?>
</div>
Instead of using the get_field() function repeatedly, you can use the get_fields() function to retrieve all the fields for a specific product category in a single call, and then access the individual fields as an array. Here's how it can be done:
<div class="full top-cat-seo">
<?php
$queriedObject = get_queried_object();
$fields = get_fields("product_cat_{$queriedObject->term_id}");
echo $fields['product_category_top_section_seo'];
?>
<?php
for ($i = 1; $i <= 4; $i++) {
$link = $fields["link_url_{$i}"];
$linkname = $fields["link_url_{$i}_name"];
if ($link) {
?>
<a class="button" href="<?php echo esc_url($link); ?>"><?php echo esc_html($linkname); ?></a>
<?php
}
}
?>
</div>

Related

WP Loop Geo + jQuery .hide() not working correctly

I have a WP loop where each post has a collection of 4 country based images (using ACF).
I only would like to output 1 image per country, however it is displaying all of 4 images per post.
<?php
$args = array( 'post_type' => 'quick_links', 'posts_per_page' => 3 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$image_au = get_field("au_image");
$image_nz = get_field("nz_image");
$image_us = get_field("us_image");
$image_gl = get_field("global_image"); //default image
?>
<script type="text/javascript">
var image_au = <?php echo json_encode($image_au['url']); ?>;
var image_nz = <?php echo json_encode($image_nz['url']); ?>;
var image_us = <?php echo json_encode($image_us['url']); ?>;
var image_gl = <?php echo json_encode($image_gl['url']); ?>;
jQuery.get("http://ipinfo.io", function (response) {
if (response.country === "AU"){
jQuery("#resultQLAU").show();
jQuery("#resultQLNZ").hide();
jQuery("#resultQLUS").hide();
jQuery("#resultQLGlobal").hide();
} else if(response.country === "NZ"){
jQuery("#resultQLNZ").show();
jQuery("#resultQLAU").hide();
jQuery("#resultQLUS").hide();
jQuery("#resultQLGlobal").hide();
} else if(response.country === "US"){
jQuery("#resultQLUS").show();
jQuery("#resultQLNZ").hide();
jQuery("#resultQLAU").hide();
jQuery("#resultQLGlobal").hide();
} else {
jQuery("#resultQLGlobal").show();
jQuery("#resultQLNZ").hide();
jQuery("#resultQLUS").hide();
jQuery("#resultQLAU").hide();
}
if(image_au === "" && image_nz === "" && image_us === "" && image_gl !== ""){
jQuery("#resultQLGlobal").show();
}
}, "jsonp");
</script>
<?php
echo '<div class="col-lg-4 col-sm-6" style="padding:2px">';
echo '<a href="' . get_field('page_url') . '" class="portfolio-box">';
?>
<div id="resultQLAU">
<img class="img-responsive" src="<?php echo $image_au['url']; ?>" alt="<?php echo $image_au['alt']; ?>" />
</div>
<div id="resultQLNZ">
<img class="img-responsive" src="<?php echo $image_nz['url']; ?>" alt="<?php echo $image_nz['alt']; ?>" />
</div>
<div id="resultQLUS">
<img class="img-responsive" src="<?php echo $image_us['url']; ?>" alt="<?php echo $image_us['alt']; ?>" />
</div>
<div id="resultQLGlobal">
<img class="img-responsive" src="<?php echo $image_gl['url']; ?>" alt="<?php echo $image_gl['alt']; ?>" />
</div>
<?php
echo '<div class="portfolio-box-caption">';
echo '<div class="portfolio-box-caption-content">';
echo '<div class="project-category text-faded">' . get_the_title() . '</div>';
echo '<div class="project-name">' . get_the_content() . '</div>';
echo '</div>';
echo '</div>';
echo '</a>';
echo '<h6 class="news-title text-center">' . get_the_title() . '<span style=""> <i class="fa fa-angle-double-right"></i></span></h6>';
echo '</div>';
endwhile;
?>
I originally had the code e.g <div id="resultQLAU" style="display:none"> and just had jQuery("#resultQLAU").show(); in script which outputed only the first
GEO image of the first post (so GEO was working correct for that 1 post)
Not sure what problem is?
Your help would be much appreciated. Thanks
You are using ID inside your loop so all the block will have the same ids which isn't good as id need to be unique. You may change this by adding a suffix/prefix depending the iteration and use classes instead.
1) add a new var the increment inside your loop like this :
$i = 0
while ( $loop->have_posts() ) : $loop->the_post();
$i++;
2) for each id append the content of $i, for example :
jQuery(".resultQLAU_<?php echo $i; ?>").show();
do this everywhere you have the id.

Php code between Tab Shortcode

I want to insert php code in between tabby tabs shortcodes.
I am using a plugin tabby tab for tab view and have added this code in my theme template:
<?php echo do_shortcode('[tabby title="Gallary Name"]
name content
[tabby title="Images"]
[tabbyending]'); ?>
I want to use a custom fields gallery under images tab using code like this:
<?php echo do_shortcode('[tabby title="Gallary Name"]
name content
[tabby title="Images"]
<?php
$i = 0;
$images = get_field('vil_pics');
if( $images ): ?>
<div>
<ul>
<?php foreach( $images as $image ): ?>
<li<?php if ( $i % 3 == 0 ) echo ' class="break"' ?>>
<a href="<?php echo $image['url']; ?>">
<img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" />
</a><p>.</p>
</li>
<?php endforeach; ?>
</ul></div>
<?php endif; ?>
[tabbyending]'); ?>
This code is not working, it's showing a blank page. How can I fix this?
Tabby uses a global variable to track what's going on, so I think either one of these will work. The first one is a little more straightforward, but the second one will definitely work.
Option 1: output everything in order:
echo do_shortcode( '[tabby title="Gallery Name"] name content' );
echo do_shortcode( '[tabby title="Images"]' );
// your php code as-is
$i = 0;
$images = get_field('vil_pics');
if( $images ): ?>
<div>
<ul>
<?php foreach( $images as $image ):
$i++ ?>
<li<?php if ( $i % 3 == 0 ) echo ' class="break"' ?>>
<a href="<?php echo $image['url']; ?>">
<img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" />
</a><p>.</p>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif;
echo do_shortcode( '[tabbyending]' );
or Option 2: save everything to a variable and output it all at once:
$output = '';
$output .= '[tabby title="Gallery Name"] name content';
$output .= '[tabby title="Images"]';
$i = 0;
$images = get_field('vil_pics');
if ( $images ) {
$output .= '<div><ul>';
foreach( $images as $image ) {
$i++;
$li_class = ( $i % 3 == 0 ) ? ' class="break"' : '';
$output .= '<li' . $li_class . '>';
$output .= '<a href="' . $image['url'] . '">';
$output .= '<img src="' . $image['sizes']['thumbnail'] . '" alt="' . $image['alt'] . '" />';
$output .= '</a><p>.</p></li>';
}
$output .= '</div></ul>';
}
$output .= '[tabbyending]';
echo do_shortcode( $output );
Note that I didn't see anything increasing $i so I added that. Everything else is as-is.

How to access ACF fields for a custom post type using 'wpdb'?

I have two WordPress installs, one is to be used as an intranet and the other is public. I need to pull in the data for a custom post type from the public site to be shown on the intranet, essentially so the admin doesn't need to enter the same data on each site.
So, far I've got this:
$wpdb = new wpdb(*CONNECTION DETAILS*);
$careers = $wpdb->get_results(
'SELECT *
FROM wp_posts
WHERE post_type = "career-post"'
);
if (!empty($careers)) {
echo '<ul id="careers-list">';
foreach ($careers as $career) {
echo '<li class="career">';
echo '<a class="wrap" href="http://domainname.com/career/'.$career->post_name.'" target="_blank">';
echo '<h2>'.$career->post_title.'</h2>';
echo get_field('career_duration') ? '<p class="duration">('.get_field('career_duration').')</p>' : '<p class="duration">(permanent)</p>';
echo '<h3>'.get_field('career_area').'</h3>';
echo '<p class="description">'.get_field('career_short_description').'</p>';
echo '</a>';
echo '</li>';
}
echo '</ul>';
}
else {
echo '<h2>Sorry, no vacancies are currently listed.</h2>';
}
Which is pulling in the slug and title as expected, but as the ACF data is stored in a different table, I am not sure how to a) access that data and b) link it to the correct post.
Fetch ACF fields for a custom post type
<?php
$wpdb = new wpdb(*CONNECTION DETAILS*);
$careers = $wpdb->get_results(
'SELECT *
FROM wp_posts
WHERE post_type = "career-post"'
);
if (!empty($careers)) {
?>
<ul id="careers-list">
<?php
foreach ($careers as $career) {
$career_duration = get_field('career_duration', $career->ID);
$career_area = get_field('career_area', $career->ID);
$career_short_description = get_field('career_short_description', $career->ID);
?>
<li class="career">
<a href="<?php echo get_permalink($career->ID); ?>" target="_blank">
<h2><?php echo get_the_title( $career->ID ); ?></h2>
<?php
if($career_duration!="")
{
?>
<p class="duration"><?php echo $career_duration;?></p>
<?php
}
else
{
?>
<p class="duration">permanent</p>
<?php
}
?>
<h3><?php echo $career_area;?></h3>
<p class="description"><?php echo $career_short_description;?></p>
</a>
</li>
<?php
}
?>
</ul>
<?php
}
else {
echo '<h2>Sorry, no vacancies are currently listed.</h2>';
}
?>
OR
<?php
$career_post_type = 'career-post';
$career_post_args=array(
'type' => $career_post_type,
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts' => -1,
'orderby' => 'name',
'order' => 'ASC',
);
$career_post_my_query = null;
$career_post_my_query = new WP_Query($career_post_args);
if( $career_post_my_query->have_posts() )
{
?>
<ul id="careers-list">
<?php
while ($career_post_my_query->have_posts()) : $career_post_my_query->the_post();
$career_duration = get_field('career_duration', $post->ID);
$career_area = get_field('career_area', $post->ID);
$career_short_description = get_field('career_short_description', $post->ID);
?>
<li class="career">
<a href="<?php echo get_permalink($post->ID); ?>" target="_blank">
<h2><?php echo get_the_title( $post->ID ); ?></h2>
<?php
if($career_duration!="")
{
?>
<p class="duration"><?php echo $career_duration;?></p>
<?php
}
else
{
?>
<p class="duration">permanent</p>
<?php
}
?>
<h3><?php echo $career_area;?></h3>
<p class="description"><?php echo $career_short_description;?></p>
</a>
</li>
<?php
endwhile;
?>
</ul>
<?php
}
else {
echo '<h2>Sorry, no vacancies are currently listed.</h2>';
}
wp_reset_query($career_post_my_query);
?>
Shital, I don't see how your second solution would work as it's not referencing the external DB?
I've tried the following (similar to your first solution) and it doesn't return anything for the ACF fields either:
foreach ($careers as $career) {
$ID = $career->ID;
$slug = $career->post_name;
$title = $career->post_title;
$duration = get_field('career_duration', $ID);
$area = get_field('career_area', $ID);
$description = get_field('career_short_description', $ID);
echo '<li class="career">';
echo '<a class="wrap" href="http://domainname.com/career/'.$slug.'" target="_blank">';
echo '<h2>'.$title.'</h2>';
echo $duration ? '<p class="duration">('.$duration.')</p>' : '<p class="duration">(permanent)</p>';
echo '<h3>'.$area.'</h3>';
echo '<p class="description">'.$description.'</p>';
echo '</a>';
echo '</li>';
}

How to arrange subtitles under a title in Yii2

I am trying to arrange some subtitles under a main tile but it is repeating the title.
<div id="downloads" class="tab-pane" role="tabpanel">
<?php
$product_id = $model->id;
$downloads_model = Printingmachinedownloads::find()->where(['productid'=>$product_id])->all();
foreach ($downloads_model as $doc) {
$doc_type = $doc['type'];
$doc_label = $doc['documentlabel'];
$doc_title = $doc['documentname'];
?>
<div class="amazingcarousel-container-1 tab_style">
<h3><?php echo $doc_type;?></h3>
<a target = '_blank' href="<?php echo Yii::$app->homeUrl?>images/printingmachine/downloads/<?php echo $doc_title; ?>">
<?php echo $doc_label ?>
</a>
</div>
<?php
}
// $doc_title = $downloads_model[0]->documentlabel;
?>
</div>
</div>
The output is:
What I need is
Brochures
abc
def
ghi
Specificationsheet
xyz
lmn
opq
Can Anyone tell me what I have to do?
Thanks in Advance
If you don't have issue with new MySQL version group by concept, you can use something like:
...
$downloads_model = Printingmachinedownloads::find()->where(['productid'=>$product_id])->groupBy(['type'])->all();
foreach($downloads_model as $doc):
<div class="amazingcarousel-container-1 tab_style">
<h3><?= type['type'] ?></h3>
$subtitles = Printingmachinedownloads::find()->where(['productid'=>$product_id, 'type' => $doc['type'] )->all();
foreach($subtitles as $subtitle):
<a target = '_blank' href="<?php echo Yii::$app->homeUrl?>images/printingmachine/downloads/<?php echo $subtitle['documentname']; ?>">
<?php echo $subtitle['documentlabel'] ?>
</a>
enforeach;
</div>
endforeach;
...
If have issue with group by you can use little non standard way, it's not best practice and effective way:
$downloads_model = Printingmachinedownloads::find()->where(['productid'=>$product_id])->orderBy(['type'=>SORT_DESC])->all();
$previous_title = ''; $iteration = 1;
foreach($downloads_model as $doc):
$subtitles = Printingmachinedownloads::find()->where(['productid'=>$product_id, 'type' => $doc['type'] )->all();
$count = count($subtitles);
$previous_title = $previous_title ?: $doc['type'];
if( $previous_title == $doc['type'] && $count == $iteration ):
<div class="amazingcarousel-container-1 tab_style">
<h3><?= $previous_title ?></h3>
foreach($subtitles as $subtitle):
<a target = '_blank' href="<?php echo Yii::$app->homeUrl?>images/printingmachine/downloads/<?php echo $subtitle['documentname']; ?>">
<?php echo $subtitle['documentlabel'] ?>
</a>
enforeach;
</div>
$previous_title = ''; $iteration = 1;
else:
$iteration++;
endif;
endforeach;
I didn't test it, but something similar should work.
But my suggestion and effective way will be you use relational tables 1 title container another related table containing sub titles.

How to concatenate if statement into a string?

Here is my code on one of my templates...
<?php while ( have_posts() ) :
the_post();
the_content();
query_posts( 'posts_per_page=5' );
endwhile; ?>
<ul id="on-going">
<?php $terms = get_terms(
'series', array(
'orderby' =>'name'));
foreach( $terms as $t ){
$t_id = $t->term_id; $series = get_option("taxonomy_$t_id");
if( $series['status_term_meta'] != 1 ) continue; ?>
<li>
<a title="See all <?php echo $t->name; ?> Episodes" href="<?php echo home_url(); ?>
/series/<?php echo $t->
slug; ?>">
<?php echo( strlen($t->
name) > 25)?substr( $t->name, 0, 25 ) . '...':$t->name; ?> </a>
<?php if(is_subbed($t->slug)) {
echo'<span class="subbedcolor small rightside"> SUBBED </span> ';
}
if(is_dubbed($t->slug)){
echo'<span class="dubbedcolor small rightside"> DUBBED </span> ';
}
?>
I want to take the part
<?php if(is_subbed($t->slug)) {
echo'<span class="subbedcolor small rightside"> SUBBED </span> ';
}
if(is_dubbed($t->slug)){
echo'<span class="dubbedcolor small rightside"> DUBBED </span> ';
}
and include it into my other template so it will show if an episode is subbed, or dubbed:
Here is the string for the other code:
$page = $page . "<li><a style='display:block;' title='" . $name . "' href='" . home_url(). "/series/" .$term->slug . "'>" . $name ."</a></li>";
How would I include the subbed or dubbed part after the closing li tag? I tried to concatenate the if statement, but I can't seem to get it to work.
Thanks so much if anyone can figure it out :D
You said that concatenation didn't work. What did you try and what didn't work?
Try this:
if(is_subbed($t->slug)) {
$page = $page.'<span class="subbedcolor small rightside"> SUBBED </span> ';
}
if(is_dubbed($t->slug)){
$page = $page.'<span class="dubbedcolor small rightside"> DUBBED </span> ';
}

Categories