marya marya - 4 months ago 21
PHP Question

Replace spaces with underscores in a custom field

In a WordPress website I want to replace spaces with underscores in the values of a custom field named

mycustomfield
and print it.

Here is the code to print a custom field:

<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'mycustomfield', true);
wp_reset_query();
?>


How do I edit that code?

Here is the final result:

A random value of the custom field
mycustomfield
when printed, will be "Las_vegas" instead of "Las Vegas".

Answer

Try this

<?php
global $wp_query;
$postid = $wp_query->post->ID;
$field_value = get_post_meta($postid, 'mycustomfield', true);
echo str_replace('_', ' ', $field_value);
wp_reset_query();
?>