• Resolved snippet24

    (@snippet24)


    Something similar to this, but instead of applying to all posts only for a specific category

    add_action( 'init', 'wpse31629_init' );
    function wpse31629_init()
    {
      add_post_type_support( 'post', 'page-attributes' );
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • Deviant Media LLC

    (@abretado1985)

    A workaround involves using the admin_init hook, combined with additional checks when rendering the post editor, to dynamically add page attribute support based on the post’s category. Below is a conceptual approach:

    1. Use the admin_init hook to set up an action for when the post is being edited.
    2. Check if the current post belongs to your specific category.
    3. If it does, add page attribute support to that post.

    Here’s how you can implement it:

    function wpse_custom_init() {
        // Hook into admin_init
        add_action( 'admin_init', 'wpse_conditional_page_attributes_support' );
    }
    
    function wpse_conditional_page_attributes_support() {
        // Check if we're on the post edit screen
        $screen = get_current_screen();
        if ( $screen->id !== 'post' ) return; // Exit if not editing a post
    
        // Check if the global $post is set, and get the post ID
        global $post;
        if ( !isset($post->ID) ) return; // Exit if no post is loaded
    
        // Check if the post belongs to the specific category
        $category_slug = 'your-category-slug'; // Replace with your category slug
        if ( has_category( $category_slug, $post->ID ) ) {
            // Add page attribute support for posts in this category
            add_post_type_support( 'post', 'page-attributes' );
        }
    }
    
    // Hook our function to init
    add_action( 'init', 'wpse_custom_init' );
    

    Replace 'your-category-slug' with the slug of the category you’re targeting. This code snippet checks the current post’s category when you’re on the post edit screen and conditionally adds page attribute support for posts that belong to the specified category.

    Note: Since this approach uses the admin_init and checks the current screen, it’s specifically tailored for the WordPress admin area and is intended to work when editing posts. This method dynamically applies the post type support feature, and it may not persist outside of the context of post editing (e.g., it won’t affect front-end displays or API responses unless those contexts also perform similar checks).

    Thread Starter snippet24

    (@snippet24)

    Thank you so much!! ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to add page atributtes to a post in a certain category only?’ is closed to new replies.