John Davidson

php - Change the Category Name with ACF inside the loop

0 comments
Message:


I have the following loop:


<?php
$args = array(
'post_type' => 'cpt-a',
'category_name' => 'my-category',
'posts_per_page' => 99,
'orderby' => 'date',
'order' => 'ASC',
'ignore_sticky_posts' => 1,
'paged' => $paged);
$loop = new WP_Query($args);
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post(); ?>

<div><?php echo get_the_content(); ?></div>
<span ><?php the_title(); ?></span>

<?php endwhile;
endif;
wp_reset_postdata();
?>

Is it possible to use a custom field (ACF) instead of "my-category"? I tried all the known options, but I could not find a working solution.



My Answer:
php
// Start the loop
if ( have_posts() ) {
while ( have_posts() ) {
the_post();

// Get the current category ID
$category_id = get_the_category()[0]->term_id;

// Get the new category name using ACF
$new_category_name = get_field('new_category_name', 'category_' . $category_id);

// Update the category name
$category = get_the_category();
$category[0]->cat_name = $new_category_name;

// Display the post with the updated category name
?>


Category:


}
}
?>


In this code snippet, we are looping through the posts and getting the current category ID for each post. We then use ACF to get the new category name based on the category ID. Finally, we update the category name and display the post with the updated category name.

Rate this post

3 of 5 based on 6605 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us