I’ve created a custom post type called ‘snippets’ where there are snippets of data like ‘address’ that the client can change.
The title of the snippets are all unique:
I have created a simple function to return these snippets however it’s not working quite right and I’m not sure why.
Function:
function get_snippet($snippet_title) {
$snippet_page = new WP_Query(array(
'post_type' => 'snippets',
'post_title' => $snippet_title
));
return $snippet_page->posts[0]->post_content;
}
Here is an example call to the function:
echo get_snippet('footer_address');
The issue is:
It will always return all the snippets and not filter by post_title.
Even if I use get_posts()
it will always return all snippets in the same order and will not return the single snippet based on the post_title.
The result is instead the equivalent to:
$snippet_page = new WP_Query(array(
'post_type' => 'snippets'
));
Why will it not filter by ‘post_title’?
Thanks
(I am also using multisite)
Here is my custom post type init code:
function snippets() {
$labels = array(
'name' => _x( 'Snippets', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Snippet', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Snippets', 'text_domain' ),
'name_admin_bar' => __( 'Snippets', 'text_domain' ),
'parent_item_colon' => __( 'Parent Item:', 'text_domain' ),
'all_items' => __( 'All Snippets', 'text_domain' ),
'add_new_item' => __( 'Add New Snippet', 'text_domain' ),
'add_new' => __( 'Add New Snippet', 'text_domain' ),
'new_item' => __( 'New Snippet', 'text_domain' ),
'edit_item' => __( 'Edit Snippet', 'text_domain' ),
'update_item' => __( 'Update Snippet', 'text_domain' ),
'view_item' => __( 'View Snippet', 'text_domain' ),
'search_items' => __( 'Search Snippet', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
);
$args = array(
'label' => __( 'snippets', 'text_domain' ),
'description' => __( 'For custom snippets of code/data.', 'text_domain' ),
'labels' => $labels,
'supports' => array( ),
'hierarchical' => false,
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'menu_icon' => 'dashicons-tagcloud',
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => false,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => false,
'capability_type' => 'page',
);
register_post_type( 'snippets', $args );
}
add_action( 'init', 'snippets', 0 );
I know that this is a very old post, but maybe someone will be searching for the solution just like I did today.
It turns out that you just need to use ‘title’ instead of ‘post_title’.
Here is an example:
If still you can not get any solution, than try below manually query:
global $wpdb;
$res = $wpdb->get_results("SELECT * FROM wp_posts where post_type='snippet' AND post_title='".$snippet_title."'");