I need to define a function in functions.php or a plugin and be able to call it inside the theme’s loop & outside.

Example; I have a $product_price = get_post_meta(get_the_ID(), 'product-price', true); defined inside the loop of all these pages;

inside home.php, index.php, archive.php, single.php, & other custom pages…

so every time I need to change something I need to go to every single of these pages and make the change… So Now I want to create a function where instead of having $product_price = get_post_meta(get_the_ID(), 'product-price', true); in every page I only call product_price(); and that’s it.

I’ve tried something like this (in both plugin & functions.php), but it’s not working

function product_title() {
    global $post;

    $args = array( "posts_per_page" => "-1" );
    $get_title = new WP_Query( $args );

    while ( $get_title->have_posts() ) : $get_title->the_post();

    return get_post_meta(get_the_ID(), 'product-price', true);

    wp_reset_postdata();

    endwhile;
}

1 Answer
1

Try use this (functions.php) :

function product_title($id) {
  $custom='CustomField'; // Your custom field here
  return get_post_meta($id, $custom, true);
}

and call func in your template (in loop and etc…):

<?php $p_title=product_title(get_the_ID()); ?>
<h3>Product : <?php echo ($P_title); ?> </h3>

Leave a Reply

Your email address will not be published. Required fields are marked *