Question

I've got two custom post types called Artists and Paintings. Both the post types have a custom field called artist name created using Advanced Custom Fields plugin. I need to be able to match the custom fields from both these post types, with each other, in order to display more information.

Pasting below only the args and loop from the query. Will post more of the code if it is necessary.

<?php
$artist_name = get_field('artist');

$args = array(
'post_type' => 'artists',
'meta_value' => $artist_name
);
$query_artist = new WP_Query( $args );

if ( $query_artist->have_posts() ) {
    while ( $query_artist->have_posts() ) {
        $query_artist->the_post(); ?>
        <p class="artist-name"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
        <?php }
} else {
    echo 'Artist not found';
}
wp_reset_postdata(); ?>

This code works properly when in the template file for the homepage but always prints out 'Artist not found' when in the search results page. I copied this code directly from the homepage template so spelling mistakes are not the problem. Been breaking my head over this for a long time. Will anyone reading this have a clue on what's happening?

Thanks.

Was it helpful?

Solution

Ok, so I've managed to finally get what I want to work but I'm not sure why the below code worked and my original didn't since both of them are similar methods to do a new query.

Here's the code if anyone else had the same problem:

<?php
// Permalink for artist
$artist_name = get_field('artist');
global $post;
$posts = get_posts( array( 'post_type' => 'artists', 'meta_value' => $artist_name ) );
if( $posts ):
   foreach( $posts as $post ) :   
    setup_postdata($post); ?>
    <p class="artist-name"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
   <?php endforeach; 
wp_reset_postdata(); 
endif; ?>

OTHER TIPS

I think that wordpress doesn't include custom types in the search automaticaly.

You can use a plugin like https://wordpress.org/plugins/advanced-custom-post-search/ or write your own function in the functions.php

function rc_add_cpts_to_search($query) {     
    // Check to verify it's search page
    if( is_search() ) {
        // Get post types
        $post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects');
        $searchable_types = array();
        // Add available post types
        if( $post_types ) {
            foreach( $post_types as $type) {
                $searchable_types[] = $type->name;
            }
        }
        $query->set( 'post_type', $searchable_types );
    }
    return $query;
}
add_action( 'pre_get_posts', 'rc_add_cpts_to_search' );

Example from http://www.remicorson.com/include-all-your-wordpress-custom-post-types-in-search/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top