Home > database >  How to get a Wordpress template file to insert different images based on the current page?
How to get a Wordpress template file to insert different images based on the current page?

Time:04-21

Just going to start by saying I am very new to web development....

I have a number of pages (100) which are all build individually in a visual editor (DIVI). They each have a set of 10-15 different images on, inserted into an identical 'wrapper'. Other than the images, the pages are identical - This was my first website and so I knew no better than this approach when I began. As I now understand, I could use a custom page template for these pages to allow scalability/re-design with much greater ease.

I understand how a template.php page could be created that pulls necessary page metadata to populate the title/subheadings etc for each page. I am thinking of writing a for loop to insert each image for the page into the repeating 'wrapper'. However, I am not sure how the template would know which images to pass into this loop based on the page visited?

I had a few thoughts on how this could be done (I am very inexperienced): a) Re-structure my wp-uploads folder to match my sitemap and get the template to insert all images in the path that matches the slug b) Upload all images for each page to the page in the back-end (not sure if this is possible) and get the template to insert all images associated with the page in question c) Get the template to loop through a database table containing all of the image names matched to the page id on which they should be found and only insert those that match the current page id

If this changes anything, all 100 pages are child-pages of pageX and their slug begins with a common word. eg:

mysite.com/pageX/commonword-page1/

mysite.com/pageX/commonword-page2/

My first time posting on here so sorry if any information is missed.

CodePudding user response:

Since you have so many pages, I wouldn't use an if statement. The best way to handle this would be to use Advanced Custom Fields and set up an image field to show on the pages post type. Then, in your code, call the custom field and that way every page dynamically show their respective image. You can find ACF in the Plugins repository on your WordPress site or download it directly from their website.

Here is the image field documentation: https://www.advancedcustomfields.com/resources/image/

The cleanest way is to set the field to use the URL of the image. Here is what would go in your code:

<?php if( get_field('field_slug') ): ?>
    <img src="<?php the_field('field_slug'); ?>" />
<?php endif; ?>

Let me know if you have any questions! :)

  • Related