Wordpress function to effect only one (custom) post type, and not every post

848 views Asked by At

I'm having an issue with a custom post type (WP Job Manager).

I am using the following code in my functions file to 'add a default image to posts that have no image attached'.

function custom_default_cover_image( $image, $args ) {
    global $post;

    if ( $image ) {
        return $image;
    }

    $image = array( 'http://website.com/image.jpg' );

    return $image;
}
add_filter( 'cover_image', 'custom_default_cover_image', 10, 2 );

However, this is adding the default image i have specified to every post. The custom post type is 'job_listing'. How do i need to change the code to make it effect only that post type?

Wordpress functions are new to me so might be an easy fix but have tried a few things and can't get it work.

Thanks for you help. Miro

2

There are 2 answers

2
rnevius On BEST ANSWER

You're looking for get_post_type():

function custom_default_cover_image( $image = null, $args = null ) {
    global $post;

    if ( get_post_type() === 'job_listing' && ! $image ) { 
        $image = array( 'http://website.com/image.jpg' );
    }

    return $image;
}
add_filter( 'cover_image', 'custom_default_cover_image', 10, 2 );
0
Pieter Goosen On

You can also use the global post object since you are invoking it

The following will also work

if ( $post->post_type == 'job_listing' ) {
    // Do something only for job_listing post type posts
}