Get featured image on Blog Index

I’ve been trying to use the “featured image” from the home (the blog index) with no luck. It’s working for every single page, but it’s not working for the home.

The code looks something like this:

// Don't use on single posts
    if (!is_single()) {
        if (is_home()) {
            if (function_exists('wp_get_attachment_thumb_url')) {
                $img = wp_get_attachment_image_src(get_post_thumbnail_id(),'full');
                $featured_image = $img[0];
            }
        } else {
            if (function_exists('wp_get_attachment_thumb_url') && has_post_thumbnail()) {
                $img = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full');
                $featured_image = $img[0];
            }
        }
        if ($featured_image) { ?>
            // A lot of code...
        <?php }
    }

I already tried to obtain the thumbnail using the _thumbnail_id meta. Same result.

This code is placed on the functions file, I believe that the issue is that it’s trying to get the loop/posts featured image.

Thanks a lot in advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

if you are referring to the ‘page for posts’, then try (only relevant section of your code shown):

if (is_home() && get_option('page_for_posts') ) {
    $img = wp_get_attachment_image_src(get_post_thumbnail_id(get_option('page_for_posts')),'full'); 
    $featured_image = $img[0];
} else {

Method 2

I’d suggest anyone doing this consider the following adjustments:

  1. Get the ID of the current page/post/index using get_queried_object(). For a blog index that’s set to a page this will return the correct page ID.
  2. If all you want is the full-sized image use wp_get_attachment_url() instead of wp_get_attachment_image_src()

Here’s a quick function I’d use to achieve this in a simpler way:

/**
 * Custom Featured Image
 */
function custom_featured_image() {
    $queried_obj = get_queried_object();

    // Don't use on single posts (JUST FOR THIS DEMO)
    if ( is_single() ) return;

    // Get the featured image ID
    $image_id = get_post_thumbnail_id( $queried_obj->ID );

    // Get the URL for the full sized image
    $image_src = wp_get_attachment_url( $image_id );

    return $image_src;
}

I personally like to avoid excessive nested conditional logic, using a function can help with this.

Method 3

This works..

<section id="banner" style="background-image: <?php if (is_home() && get_option('page_for_posts') ) {
    $blog_home_id = get_option( 'page_for_posts' );
    echo 'url('.get_the_post_thumbnail_url($blog_home_id, 'full').')'; 
} else { 
echo 'url('.get_the_post_thumbnail_url($post->ID, 'full').')';
}
?>;">

Hope this helps!

Method 4

You have 2 quick options, via the template file using the_post_thumbnail for the loop. I assume your outputting the data in a typical blog format and thus your function above won’t work or act very weird inside the loop.

Instead try something like this in the actual template file where your main loop is (maybe index.php or loop.php) :

  //loop starts
   if ( has_post_thumbnail() ) { 
   the_post_thumbnail();
   }
   //the_content(); and other stuff
   //loop ends

Or if you want to use an action instead to alter the main loop you can use pre_get_posts, for example in your functions.php file.

Something like:

add_action( 'pre_get_posts', 'add_featured_image' );

function add_featured_image( $query ) {

    if( $query->is_main_query() && $query->is_home() ) {
        //your image code
    }

}

Notice that the above is checking 2 parameters, the main query and the home page, it is very important to check if it is the main query, otherwise it will alter all queries.

Reference:http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

Method 5

When you are in the “posts page” $post will start with the first “post” in the loop.
One way could be by using the “queried object”.

Print $wp_query and you will see:
[queried_object]

testing fails with Jest

All we need is an easy explanation of the problem, so here it is. I have got a code for which I have to perform tests on. After installing Jest and using it with enzyme for testing different components, now I have to check that only Authorized tenants can access my website. Both client side […]

0 comments

MUI error: Cannot read properties of undefined (reading ‘drawer’)

All we need is an easy explanation of the problem, so here it is. I am using on project MUI v5.0.2. One week ago my project worked correctly (there were no errors), but today an error appeared out of nowhere (there were no changes in the code) Error: TypeError: Cannot read properties of undefined (reading […]

0 comments

React icons not loading with webpack

All we need is an easy explanation of the problem, so here it is. I am trying to use react-icons in my project https://github.com/gorangajic/react-icons My webpack file looks like this : import webpack from ‘webpack’; import path from ‘path’; const GLOBALS = { ‘process.env.NODE_ENV’: JSON.stringify(‘development’), __DEV__: true }; export default { debug: true, devtool: ‘cheap-module-eval-source-map’, […]

0 comments

React setState hook not working with useEffect

All we need is an easy explanation of the problem, so here it is. I have the following code. The idea is to create a simple loading for a mock component const [loading, setLoading] = useState(false) function mockLoading () { setLoading(true) console.log(‘1’, loading) setTimeout(() => { setLoading(false) console.log(‘2’, loading) }, 3000) } useEffect(() => { […]

0 comments

Incrementing value and setting it as var to onClick event

All we need is an easy explanation of the problem, so here it is. I am facing a really odd problem which causes feel like “whatever you cal” First of all here is the code: renderImages = () => { let i = 0; const arr = [ “https://truffle-assets.imgix.net/pxqrocxwsjcc_6OcJeUMaWIYOmKgsK6IwWc_galaxy-cupcakes_squareThumbnail_en-US.jpeg”, “https://sallysbakingaddiction.com/wp-content/uploads/2017/06/moist-chocolate-cupcakes-5.jpg”, “http://is4.mzstatic.com/image/thumb/Purple127/v4/74/47/31/7447317e-9844-3ee0-d189-661a55c94abe/source/1200x630bb.jpg”, “https://i.pinimg.com/736x/55/03/94/550394c428e268868aa73e509302b84c–neopolitan-cupcakes-ice-cream-cupcakes.jpg” ]; return arr.map((item) […]

0 comments

Jest test (ReferenceError: google is not defined) ReactJS and Google Charts

All we need is an easy explanation of the problem, so here it is. I’m using the google script tag from their CDN (tried body and head) <script src=”https://wikitags.com/js/googlecharts.min.js”></script> The Google Chart in my app works fine, however it’s causing my Jest tests to fail… Inside of the <ChartComponent /> componentDidMount() { // Load the […]

0 comments

How do i use componentWillReceiveProps() correctly?

All we need is an easy explanation of the problem, so here it is. I’m trying to update a child component as soon as it recieves new props. However, componentWillReceiveProps() in my child component is called before the props have actually updated. After reading this article i do understand why but it doesn’t explain me […]

0 comments

Multiple event handlers for the same event and element with Reactjs

All we need is an easy explanation of the problem, so here it is. I’m writing an extended version of the input element. Here is a simplified version of it: var MyInput = React.createClass({ render: function () { return ( <div> <input type=”text” onChange={this.changeHandler} {…this.props} /> </div> ); }, changeHandler: function(event){ console.log(‘Trigger me first’); } […]

0 comments

React-datepicker: enable to set date only if it 18 years old and above

All we need is an easy explanation of the problem, so here it is. I have a form where a user can submit some info needed One of the fields is a Date of Birth I am using react-datepicker package for that specific field A piece of code looks like this: <label> <DatePicker autoComplete=’off’ dateFormatCalendar=”MMMM” […]

0 comments

Throttle function (lodash inspired) to handle resize event using React hooks only (with Sandbox)

All we need is an easy explanation of the problem, so here it is. Sorry for the long question, but I needed to make an introduction in order to make it clearer. I was in need of some code to toggle between my Headers components <HeaderDesktop> and <MobileHeader>. At first I was using CSS media […]

0 comments

Get featured image on Blog Index
— note: queried_object will/might be empty in some pages

// get_the_post_thumbnail_url( get_queried_object(), 'fullsize' );

// or

function ABC_get_the_thumbnail_url() {

    $queried_object = get_queried_object();

    $thumbnail_url = get_the_post_thumbnail_url( $queried_object, 'fullsize' );

    if ( ! $thumbnail_url ) {

        return get_template_directory_uri() . '/your-path/default-image.jpg';

        // or from a default option

    }

    return $thumbnail_url;

}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x