Skip to content

Instantly share code, notes, and snippets.

@jasperf
Last active September 5, 2023 00:34
Show Gist options
  • Save jasperf/767efe5982e5fc6eb42f16a20679097e to your computer and use it in GitHub Desktop.
Save jasperf/767efe5982e5fc6eb42f16a20679097e to your computer and use it in GitHub Desktop.
Append an ACF field after WooCommerce Product title for specific pages
<?php
/**
* This solutions uses WooCommerce's built in `woocommerce_after_shop_loop_item_title`
* action to load the ACF field after the shop loop item title
*
* Much less memory intense than initial solution than direct title manipulation
*/
function add_custom_text_after_product_title_single() {
if ( ( is_front_page() || is_shop() ) ) {
// Get the value of the ACF field (replace 'your_acf_field_name' with the actual field name)
$acf_field_value = get_field( 'kleding_prijs_vanaf' );
if ($acf_field_value) {
echo '<div class="acf-field-content">' . esc_html($acf_field_value) . '</div>';
}
}
}
add_action('woocommerce_after_shop_loop_item_title', 'add_custom_text_after_product_title_single', 15);
@jasperf
Copy link
Author

jasperf commented Sep 4, 2023

Much less memory intense than initial solution. This solutions uses WooCommerce's built in `woocommerce_after_shop_loop_item_title action to load the ACF field after the shop loop item title:

function add_custom_text_after_product_title_single() {
    if ( ( is_front_page() || is_shop() ) ) {
        // Get the value of the ACF field (replace 'your_acf_field_name' with the actual field name)
            $acf_field_value = get_field( 'kleding_prijs_vanaf' );
            if ($acf_field_value) {
                echo '<div class="acf-field-content">' . esc_html($acf_field_value) . '</div>';
            }
    }
}
add_action('woocommerce_after_shop_loop_item_title', 'add_custom_text_after_product_title_single', 15);
/**
* Memory intensive solution I no longer use:
* 
*/ 
function custom_append_acf_to_product_title( $title, $post_id ) {
    // Check if it's a WooCommerce product post type
    if ( 'product' === get_post_type( $post_id ) ) {
        // Check if it's the frontpage or the products page
        if ( ( is_front_page() || is_shop() ) ) {
            // Get the value of the ACF field (replace 'your_acf_field_name' with the actual field name)
            $acf_field_value = get_field( 'your_acf_field_name', $post_id );
            
            // Append the ACF field value after the product title
            if ( $acf_field_value ) {
                $title .= '<a href="' . get_permalink( $post_id ) . '">' . esc_html( get_the_title( $post_id ) ) . '</a>';
                $title .= '<br />' . esc_html( $acf_field_value );
            }
        }
    }

    return $title;
}
add_filter( 'the_title', 'custom_append_acf_to_product_title', 10, 2 );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment