How to replace get_page_by_title() with WP_Query()

  Kiến thức lập trình

I have a function in a WordPress plugin which downloads an image from an external URL and uploads it to the Media Library, but first it checks to make sure the file doesn’t already exist in the Media Library.

The code that ChatGPT in all it’s wisdom gave me to check for the files existence is:

    $filename = basename($image_url);

    // Check if the file already exists in the media library.
    $attachment = get_page_by_title($filename, OBJECT, 'attachment');

    if(!$attachment){
        // File doesn't already exist, so do stuff.
    } else {
        // File already exists.  Move on with your life.
    }

Now, there appears to be absolutely nothing wrong with this code at all and it works absolutely perfectly… except that WordPress’s error display is tell me that “get_page_by_title” is deprecated since WordPress 6.2.0 and that I should use WP_Query instead.

The problem is that I have been Googling how to use WP_Query as a replacement for get_page_by_title and it seems that I’m pretty much going to have to write about 50 lines of code to replace just this one single line. Seems a little counter-intuitive to me.

The beautiful thing about “get_page_by_title” is that I can then get the ID of the existing file with “$attachment->ID” (which I need).

What I’m after is the quickest, most code-efficient way of using WP_Query to get the same result that I’m currently getting from “get_page_by_title” so that I can future-proof this puppy.

(NB: This is something that even ChatGPT can’t answer! I actually managed to break ChatGPT with this! It just sat there with it’s thinking indicator spinning forever and could never give me an answer! LOL!)

LEAVE A COMMENT