0

I want to add "custom built" to the front of every product title in a certain category.

<?php 
$args = array('post_type' => 'product',
              'tax_query'=> array(
             array('taxonomy' => 'product_cat',
                   'field'    => 'id',
                   'terms'    => '3439',),),
              'posts_per_page'    => -1,
         );
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) 
   {
      while ( $loop->have_posts() ) : $loop->the_post();
         $prod_id = get_the_ID();
         $my_post = array('ID'=> $prod_id,
                          'post_title'   => 'custom built', // I want to add 'custom built' not replace the whole title
              );
         wp_update_post( $my_post );
      endwhile;
   }
wp_reset_postdata();
?>
  • 3
    You can use 'post_title' => 'custom built ' . get_the_title(). Or you could use a filter without statically changing the post title. – Sally CJ Sep 27 '18 at 6:00
1

I would use a filter. Sometimes things change and strings have to be translated and so on:

function my_custom_built_title( $title, $post_id ) {
    $post  = get_post( $post_id );
    if ( 'product' == $post->post_type ) {
        $terms = wp_get_post_terms( $post->ID, 'product_cat', [ 'fields' => 'ids' ] );
        if ( in_array( '3439', $terms ) ) {
            $title = 'Custom build ' . $title;
        }
    }

    return $title;
}
add_filter( 'the_title', 'my_custom_built_title', 10, 2 );

I did not test it but it could be a starting point.

1

Alternative, you can add it simply with CSS ::after . You can add this:

.product-title::after{
    content:'custom built';
    position:absolute;
    right:0;
    top:0;
}

.product-title{
    position:relative;
}

Just replace .product-title with the class of your title.

  • I'm sure the OP wants the title be visible in the source code, and not just visually. – Sally CJ Sep 27 '18 at 12:52
  • 1
    How can you be sure of that, he didn't mention anything relevant to it. – dominotrix Sep 28 '18 at 12:50
  • You're right @dominotrix (and +1 for that), and I'm sorry about the "I'm sure" part, which should've been "I think". – Sally CJ Sep 28 '18 at 13:02
  • Thats an interesting option but not really what I'm looking for – Tsea Sep 28 '18 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.