Support » Developing with WordPress » Getting a specific post with WordPress – Finding a good practice

  • I have a custom post type, called Models. I’m trying to retrive a specific post/model (‘model-a’).

    What would be a best practice for achieving this?

    I read this can be done with get_page_by_title function. However I tried this code:
    print_r(get_page_by_title('model-a', OBJECT, 'model'));
    and this code:

    $page = get_page_by_title('model-a', OBJECT, 'model')
    print_r($page)

    and it printed nothing to my screen.
    Print_r should print “Prints human-readable information about a variable” so I understand there is some problem with my get_page_by_id.

    Any suggestions?

    • This topic was modified 1 month, 1 week ago by  benherzliya. Reason: style
    • This topic was modified 1 month, 1 week ago by  benherzliya.
Viewing 2 replies - 1 through 2 (of 2 total)
  • What’s the context here? What are you retrieving it for and what will you be doing with it?

    With your specific code the problem appears to be that you are using the model slug, rather than the title. Try:

    get_page_by_path('model-a', OBJECT, 'model')
    
    • This reply was modified 1 month, 1 week ago by  Jacob Peattie.

    Use get_post() using the post ID for ‘model-a’

    $post_7 = get_post( 7 );
    $title = $post_7->post_title;

    print_r is for arrays, what you are dealing with is an object you need var_dump

    var_dump($post_7);

    https://developer.wordpress.org/reference/functions/get_post/

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.