John Davidson

php - Wordpress - Set a Drop Down For Featured Image To Change Background Position Depending on Page

0 comments
Message:


Right now my featured image for a page template is pulled from the standard Featured Image option on the right side of the new page.


I have my CSS in my stylesheet that says object-fit: cover since it's an absolute image instead of a background image


Each image is positioned a little differently and what i'd like to do is make it so that i can set a specific object-position: x x for each image.


So, for one image, if it's cutting off someones head, i could change it to object-position: center bottom; for example or vice versa.


Does anyone know the best way of doing this ? Any way for some plugin that would allow me to dictate lets say 3 options based off a drop down from the backend of WP like:


Background:
Option 1: center top
Option 2: center
Option 3: center bottom


And then in the CSS i could set a class that would correspond to those? This way each featured image doesn't need to be one way.


Thanks!



My Answer:
One way to achieve this is by creating a custom meta box for the featured image in the WordPress backend. You can use a plugin like Advanced Custom Fields to create a dropdown field with the options you mentioned (center top, center, center bottom).

Once you have set up the custom meta box, you can retrieve the selected option in your template file and use it to set the object-position property in your CSS. Here's an example of how you can do this:

1. Install and activate the Advanced Custom Fields plugin.
2. Create a new field group and add a dropdown field with the options center top, center, and center bottom.
3. Assign this field group to the page template where you want to use it.
4. In your template file, retrieve the selected option using the get_field() function provided by Advanced Custom Fields. For example:

php
$background_position = get_field('background_position');


5. Use the $background_position variable to set the object-position property in your CSS. For example:

css
.featured-image {
object-fit: cover;
object-position: ;
}


By following these steps, you can create a dropdown field in the WordPress backend to set the background position for each featured image on a page-by-page basis.

Rate this post

5 of 5 based on 1104 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us