Adding additional content on post depending on post categories

admin2025-06-04  1

I want to add content to a post dependent on the post categories.

I have found the following code, and it works fine on the posts. But when I try to load a page it comes up with no content.

function my_category_content ( $content ) {
    global $post;
    if ( is_single() ) {
        if ( in_category( "", $post->ID ) ) {
            $content .= 'Only showing up on the categories named mini [product_category category="mini" limit="12" columns="4" orderby="date" order="desc"]';
        }
        return $content;
    } 
} 
add_filter( 'the_content', 'my_category_content' );

I want to add content to a post dependent on the post categories.

I have found the following code, and it works fine on the posts. But when I try to load a page it comes up with no content.

function my_category_content ( $content ) {
    global $post;
    if ( is_single() ) {
        if ( in_category( "", $post->ID ) ) {
            $content .= 'Only showing up on the categories named mini [product_category category="mini" limit="12" columns="4" orderby="date" order="desc"]';
        }
        return $content;
    } 
} 
add_filter( 'the_content', 'my_category_content' );
Share Improve this question edited Jan 6, 2019 at 2:35 butlerblog 5,1413 gold badges28 silver badges44 bronze badges asked Jan 5, 2019 at 20:55 Mark ClowesMark Clowes 1
Add a comment  | 

1 Answer 1

Reset to default 1

The problem is that you are returning $content from within a conditional statement that could potentially resolve as false (and will, in the case of pages, because is_single() does not apply to pages).

Move your return to outside all "if" conditions to make sure that $content is always returned, regardless of whether it is filtered or not:

function my_category_content ( $content ) {
    global $post;
    if ( is_single() ) {
        if ( in_category( "", $post->ID ) ) {
            $content .= 'Only showing up on the categories named mini [product_category category="mini" limit="12" columns="4" orderby="date" order="desc"]';
        }
    }
    return $content;
} 
add_filter( 'the_content', 'my_category_content' );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749040415a315851.html

最新回复(0)