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
2
Answers
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…
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:
Instead of using the
get_field()
function repeatedly, you can use theget_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: