Home > Software engineering >  Wordpress: changing a posts content , even if it is empty
Wordpress: changing a posts content , even if it is empty

Time:04-29

I'm trying to change the_content of Wordpress posts in the single page (woocommerce, it's products) using the filterhook “the_content", which works fairly neat – only if there IS NO CONTENT in that post (product without detailed description) my theme doesn't even show the content container, thus never even calling the_content. I do not have access to the functions, I insert snippets – whrere would I have to check against empty content, and how could I alter it (can I, at all?) without updating the post in the DB?

Here's what works, if the content consists of even a single character:


add_filter('the_content','produktbeschrieb',-1);

function produktbeschrieb($content) {
    $kategorien = get_the_term_list( $post->ID, 'product_cat', '', ', ') ;
    if ( is_singular() && in_the_loop() && is_main_query() ) {  
        if(str_contains($kategorien,'R&F Pigment Sticks')){
              return $content."<p>R&F Pigment Sticks® sind Ölfarben, die so viel Wachs enthalten, dass die Farbe in Stäbchenform gegossen werden kann. </p>";
    }
    else {
         return $content;}
}

CodePudding user response:

The solution may depend a little on the theme you are using. But I have tested the following and it works for me. I believe by default if there is no description, WooCommerce doesn't add the description tab, so you need to add it back when it is a product with an empty description, then setup the value for when the description is empty by making use of the filter you have already written.

add_filter('the_content','produktbeschrieb',-1);
function produktbeschrieb($content) {
    $kategorien = get_the_term_list( $post->ID, 'product_cat', '', ', ') ;
    if ( is_singular() && in_the_loop() && is_main_query() ) {  
        if(str_contains($kategorien,'R&amp;F Pigment Sticks')){
              return $content."<p>R&F Pigment Sticks® sind Ölfarben, die so viel Wachs enthalten, dass die Farbe in Stäbchenform gegossen werden kann. </p>";
    }
    else {
         return $content;}
}

function woocommerce_empty_description_callback() {
    global $product;
    if( is_product() && empty( $product->get_description() ) ) {
        echo apply_filters( 'the_content', '' );
    }
}

function jt_woocommerce_default_product_tabs($tabs) {
    if ( empty( $tabs['description'] ) ) {
        $tabs['description'] = array(
            'title'    => __( 'Description', 'woocommerce' ),
            'priority' => 10,
            'callback' => 'woocommerce_empty_description_callback',
        );
    }
    return $tabs;
}
add_filter( 'woocommerce_product_tabs', 'jt_woocommerce_default_product_tabs' );
  • Related