• I have the following within a single post template to bring in an image based on the value of a custom field (named Model). It works fine apart from the spaces within the image name that I would like replacing with underscores. I have been playing around with str_replace but can’t seem to get it to work.

    <img src="../../../images/buyers-guide/<?php $model = str_replace(" ","_","Model"); echo get_post_meta($post->ID, $model, true); ?>.jpg" />

    I am a bit of a novice with PHP so please be nice!

Viewing 5 replies - 1 through 5 (of 5 total)
  • Try:

    <?php $model = str_replace(' ', '_',  get_post_meta($post->ID, $model, true) ); ?>
    <img src="<?php echo get_stylesheet_uri();?>/images/buyers-guide/<?php echo $model;?>.jpg" />

    Thread Starter elhashbrown

    (@elhashbrown)

    Thanks but this returned an image name of Array.jpg

    You missed the need for $model="Model"; somewhere in there as Model is the original name of the custom field.

    I tried the following but it just brought back the spaces:

    <?php $modela="Model"; $model = str_replace(' ', '_',  get_post_meta($post->ID, $modela, true) ); ?>
    <img src="../../../images/buyers-guide/<?php echo $model;?>.jpg" />

    try:

    <img src="../../../images/buyers-guide/<?php $model = "Model"; echo str_replace(" ","_",get_post_meta($post->ID, $model, true)); ?>.jpg" />

    Thread Starter elhashbrown

    (@elhashbrown)

    No, again the result came through but the spaces are still there. This is within a Thematic child theme if that makes any difference…

    Thread Starter elhashbrown

    (@elhashbrown)

    I still haven’t managed to work this out but I found a work around. The code was working but something in WordPress wouldn’t allow spaces to be made to underscores in the url. What I did was to put underscores in the custom field and then using the original code turning them to space where needed. Thanks to those who helped.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘replacing spaces within a string’ is closed to new replies.