Update some (not all) post titles with custom field values before running the Loop

Question

In this project, there are custom posts with a variety of titles. In each post with the title that is the name of a person (first name, last name), there is a custom field (custom_title) that can hold an alternate name (last name, first name).

In order to display the names in a useful way in the custom archive page, the object is to check for a value in the custom_title field and if present update the post title with the custom title. After all of the applicable titles have been updated, the query must sort all of the posts by title, all the while recognizing the updated titles.

Using the code below, the original titles of the name articles are updated with the custom titles, but the sort order doesn’t change–it still sorts by the original title.

Thanks for taking the time to help!

    function cchs_swap_title( $updatedTitle) 
    {
        $customTitle = get_post_meta( get_the_ID(), 'custom_title', true);
        if(!empty($customTitle))
        {
            $updatedTitle = $customTitle;
        }
        return $updatedTitle;
    }
    add_filter( 'the_title', 'cchs_swap_title');
    
    function cchs_archives_orderby( $the_query ) {
        if(!is_admin() && $the_query->is_main_query())
        {
            $the_query->set( 'orderby', 'title' );
            $the_query->set( 'order', 'DESC' );
            
        }
    }
    add_action( 'pre_get_posts', 'cchs_archives_orderby', 99999 );      

    $args = array(
        'post_type'         => 'cchs_article',
        'posts_per_page'    => -1
    );
    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) : 
        while ( $the_query->have_posts() ) : $the_query->the_post();
            get_template_part( 'template-parts/content', 'archive-cchs_article');
        endwhile;
        wp_reset_postdata();
    else :
        get_template_part( 'template-parts/content', 'none' );
    endif;

0
P. Britten 1 month 2021-10-20T18:08:41-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse