Trying to understand custom fields in WordPress

2019-08-27 17:04发布

I'm trying to make my single.php page show more details about each project/item in a portfolio, with multiple larger image files that will display with captions to the right of the project description.

I'm thinking the best way to approach this would be to use the 'featured image' for the thumbnail display on the homepage which seems to be working now, but I've been trying to figure out Custom Fields to use for my other images (image1, image2, image3). I can't figure it out.

I go to "Enter new" under Custom Fields from the admin screen, enter image1 for the name. What goes in the Value field? How do I get it to work? I know I need to add some code to my single.php page... but what? And when/where do I upload the images themselves?

Any help would be greatly appreciated! I'm a little dense in the PHP department...

标签: wordpress
1条回答
放我归山
2楼-- · 2019-08-27 17:12

Have look at your single.php file. You will find the following lines, one near the top, the other lower down.

<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
...
...
<?php endwhile; // end of the loop. ?>

Anything between these two lines will be applied over and over, once per blog post that happens to be displayed by that template file. So you should put your magic between those lines.

What you put there will be a mix of HTML and PHP. For instance, you might use this line:

<img src="<?php echo get_post_meta($post->ID, 'image1', true) ?>"/>

which combines

<img src=""/>

with

<?php echo get_post_meta($post->ID, 'image1', true) ?>

The PHP line looks up whatever value you have entered for the custom field named 'image1'. If you look at the HTML I used, you will see that this value is being placed inside the 'src' attribute. In other words, the value associated with 'image1' should be the url of that image.

You can expand upon this basic idea, but that's where your own creativity will have to come in.

[Is this not a repeated question?]

查看更多
登录 后发表回答