Coder Social home page Coder Social logo

posttypes's Introduction

PostTypes v2.2

tests codecov Latest Stable Version Total Downloads License

Simple WordPress custom post types.

Requirements

Installation

Install with composer

Run the following in your terminal to install PostTypes with Composer.

$ composer require jjgrainger/posttypes

PostTypes uses PSR-4 autoloading and can be used with the Composer's autoloader. Below is a basic example of getting started, though your setup may be different depending on how you are using Composer.

require __DIR__ . '/vendor/autoload.php';

use PostTypes\PostType;

$books = new PostType( 'book' );

$books->register();

See Composer's basic usage guide for details on working with Composer and autoloading.

Basic Usage

Below is a basic example of setting up a simple book post type with a genre taxonomy. For more information, check out the online documentation here.

// Require the Composer autoloader.
require __DIR__ . '/vendor/autoload.php';

// Import PostTypes.
use PostTypes\PostType;
use PostTypes\Taxonomy;

// Create a book post type.
$books = new PostType( 'book' );

// Attach the genre taxonomy (which is created below).
$books->taxonomy( 'genre' );

// Hide the date and author columns.
$books->columns()->hide( [ 'date', 'author' ] );

// Set the Books menu icon.
$books->icon( 'dashicons-book-alt' );

// Register the post type to WordPress.
$books->register();

// Create a genre taxonomy.
$genres = new Taxonomy( 'genre' );

// Set options for the taxonomy.
$genres->options( [
    'hierarchical' => false,
] );

// Register the taxonomy to WordPress.
$genres->register();

Notes

Author

Joe Grainger

posttypes's People

Contributors

aviadpriel avatar aymanalzarrad avatar bookwyrm avatar jjgrainger avatar jorisvm avatar joshuacrewe avatar lapubell avatar mav2287 avatar mwdelaney avatar noplanman avatar shwethakpradeep avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

posttypes's Issues

Explore using PHP Traits for certain methods

Between PostType and Taxonomy classes, there is repeated code around the names, labels, options, and column methods. Consider using PHP traits to reduce duplicate code and make it easier to maintain, while not over engineering the project.

Traits could as be used for cases such as pluralizing names with regards to PR #22

Ultimate proofing

To be a good boy and create an issue before the PR (even though I've already started work on this ๐Ÿ˜)

Basically, I've proofread the entire documentation and will create different PRs that bundle certain changes (like typos, grammar, code examples, etc.) to make it easier to work through.

As I make PRs, I'll list them here to keep everything sane.

Best work through these in order, so that rebasing / merging is easier ๐Ÿ‘

  • Copy-paste fixes (PR #33)
  • Fix typos and spelling mistakes (PR #34)
  • Various grammar and wording corrections. (PR #35)
  • Improve code examples (PR #36)
  • Various touch ups (PR #37)

CPT Slug Pluralization

When creating a new CPT, if the name ends in Y then we get bad grammer in the post archive permalink.

Example:
CPT Name: "facility"

$f = new PostType('facility');

Now, when visiting the post archive, the permalink says /facilitys instead of /facilities.

Automatic post type names by slug not working on v1.1.1

Post type name, singular, and plural are not generated automatically from slug on CPT creation.
This has happened after updating to the last release v1.1.1.

I've solved it by forcing the version 1.0 on the composer.json.

Best regards,

Package ramsey/array_column is abandoned

I have the following set up for a Wordpress install :

$ cat composer.json
{
    "name": "wordpress-install",
    "description": "A Wordpress site",
    "type": "project",
    "license": "MIT",
    "require": {
        "php": ">=5.6",
        "wp-cli/wp-cli": "^1.1",
        "vlucas/phpdotenv": "^2.4",
        "johnpbloch/wordpress": "4.8.*"
    },
    "extra": {
        "wordpress-install-dir": "public/wp"
    }
}

When installing PostTypes via composer I use the following command with the following output :

$ composer require jjgrainger/posttypes

Using version ^2.0 for jjgrainger/posttypes
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing jjgrainger/posttypes (2.0.1): Downloading (100%)
Package ramsey/array_column is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files

$

The key notification being Package ramsey/array_column is abandoned, you should avoid using it. No replacement was suggested.

What do you reckon?

Compatability with attachment post type

hello
allow me a quick question hiding e.g. the 'author' column for posts works just fine - was trying to use the same code for post type 'attachment' but couldn't get the author column to hide?

am I missing something here?

this is what I used:
$pt_attachment = new PostType( 'attachment' ); $pt_attachment->columns()->hide( 'author']);

Add unit tests

I've been wanting to add unit tests for a while but wasn't sure how. After some research, I've stumbled across a few interesting articles and tools that have shed some light on how to do this.

It has become clear that there are a couple of issues with how the class has been made so far.

Calling hooks in the class constructor

Though hooks aren't specifically called in the __construct() method, there is an initialize() method that is. This method adds all of the hooks the class registers to register post types, taxonomies and columns. Having initialize() called in the constructor makes it difficult to test PostTypes in isolation of WordPress.

To fix this, I'm looking at renaming the initialize() method to register(). This will allow PostTypes to be tested in isolation of WordPress, as the method that hooks into WordPress has to be called explicitly. However, Doing this will mean the developer has to call register() themselves in order to register their post type.

$books = new PostTypes('book');

$books->taxonomy('genre');

// ... Additional post type work here

// Register the post type to WordPress
$books->register();

Concrete dependencies and dependency injection

PostTypes has 3 Classes, PostType, Columns and Taxonomy. PostType is the main class that handles everything from registering post types, taxonomies and modifying the admin columns.

Both Columns and Taxonomy are helper classes. They only really store information in a structured way to be used by PostType later. These classes are explicitly created in the __construct method.

Though this won't necessarily cause issues, it's still not good practice. So may need to look into alternatives to instantiating these additional classes.

Use of globals

There are some WordPress globals used inside some methods. Most seem unnecessary so should be simple enough to remove.

Positives

Despite the issues raised, I feel quite positive. The research has helped to clarify some principles for the class and how to approach unit testing it.

  • PostType's properties should define the state of the post type (in isolation of WordPress)
  • PostType's methods should modify the state of the post type (in isolation of WordPress)
  • The register() method should be explicitly called to hook into WordPress
  • Additional methods used to run in WordPress hooks can be tested in isolation of WordPress by checking that they return desired state.

I'll will most likely edit/comment on this issue as I work on it

t10ns

Hi, class looks great and works well, but I haven't managed to get the t10ns working.

I added the this via composer to my theme (if i require it to my vendor dir, the t10ns won't be found). I could translate all the strings ok, but the t10ns don't actually work.

The issue is unfortunately with using a variable for the text-domain for t10ns. Otto sums it up nicely in the following article (it's old but still relevant).

http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/

Basically, the get_text function suite doesn't parse PHP. It only searches through the code for __() _e() etc. The textdomain must therefore be a string.

Did you ever get this working with a provided textdomain for the object instance?

<?php
    $case = new PostType('case');
    $case->translation('shipyard');
?>

As i said, I can grab the t10ns via poedit, but the translations are not show in the backend.

Add full documentation

After the changes made for v2.0 using a single README for documentation just won't do!

Create a small Jekyll blog in /docs folder of the project, hosted with Github Pages.

Repeating field?

It would be great to have repeating fields or sets of fields supported by this library.

taxonomy - show_admin_column

screen shot 2017-06-29 at 2 08 08 pm

using "show_admin_column" as an option when creating a taxonomy I'm getting duplicate columns in the WP admin - see screenshot.

Add CPT as submenu

Hello, could you add a functionality to be able to add the CPT within a main menu? Because this currently creates a main menu, but I want to have the ability to convert it into a submenu.
image
As you can see I want to add more options to the 'register_post_type' but it does not work, in the end it does not show it, it only shows the keys that you have predefined
https://jsoneditoronline.org/?id=a876f50b0416419a9b239e1b5c00de84
Could you add this ?

Add column to POST

Hello, can I add columns to the POST type of the wordpress core?
I'm trying this but I have no results

$postcolumn = new PostType('post');
$postcolumn->columns()->add([
    'shortcode'  => __('Shortcode', 'tx' ),
]);

Add default column populate method?

In my usecase, i added serval post metas in columns, is there any way to set default column polulate method? so we can keep the code more dry?

maybe add a method populateDefault like the code below?

$client = new PostType('client');

$client->columns()
     ->hide([
         'title',
         'date',
     ])
     ->add([
         '_name'      => __('Name'),
         '_deal_date' => __('Deal time'),
        '_is_dealed'     => __('Price'),
         '_age'       => __('Age'),
         '_phone'     => __('Phone'),
         '_price'     => __('Price'),
     ])
    ->populateDefault(function ($column, $post_id)
    {
        echo get_post_meta($post_id, $column, true);
    })
   ->populate('_is_dealed', function ($column, $post_id)
     {
         $deal_price = get_post_meta($post_id, 'deal_price');

         echo ($deal_price) ? '<span class="is-success">Dealed</span>' : '<span class="is-default">not dealed</span>';
     });

Conflict with WooCommerce admin columns

Using PostTypes on WooCommerce 'product' post type seems to create duplicate Product Category and Product Type admin column values.

Repro:

  1. Install WooCommerce
  2. Import dummy data
  3. new PostType('product');
  4. Have a look at the Products admin table

Expected result:
admincols2

Actual result:
admincols

Workaround:

<?php

    $product->columns()->populate('product_cat', function() {
       // do nothing
    });

    $product->columns()->populate('product_type', function() {
        // do nothing
    });

I'm pretty sure this doesn't really qualify as a 'bug'. However, it took me a while to figure out what's going on while developing a bigger ecommerce site. Could we perhaps add a note to the documentation about this?

Thanks for this excellent library!

Add multiple taxonomies and post types to object

Currently,

  • Only one taxonomy can be added to a post type via the PostType taxonomy() method.
  • Only one post type can be added to a taxonomy via the Taxonomy posttype() method.

Update these methods so they can also accept an array so multiple taxonomies/post types can be added to an object in a single method call.

problem registering same taxonomy for different post type

Hi, I love your tool, but in this version there's a problem when registering the same custom taxonomy for different post type.
example:

  $gallery_options = [
        'has_archive' => true,
        'supports' => array("title", "editor", "author", "thumbnail"),
        'menu_position' => 5
    ];
    $gallery_names = [
        'name' => 'gallery',
        'singular' => 'Gallery',
        'plural' => 'Gallery',
        'slug' => 'gallery'
    ];
    $gallery = new PostType($gallery_names, $gallery_options);

 $marca_names = [
        'name' => 'marca',
        'singular' => 'Marca',
        'plural' => 'Marche',
        'slug' => 'marca'
    ];
    $marca_options = [
        'hierarchical' => false
    ];
$gallery->taxonomy($marca_names, $marca_options);
...
 $video = new PostType($video_names, $video_options);
 $video->taxonomy("marca");

I think the problem is in
if (taxonomy_exists($names['name'])) { $this->existingTaxonomies[] = $names['name'];

in taxonomy function, it return false.

Do you experienced the same issue?

Add translation support with textdomains

In light of #66 and having a similar issue, I was thinking how to add translation support to the library.
So I've extended the PostType in one of my projects to add translation support with loading a textdomain.

https://developer.wordpress.org/reference/functions/load_textdomain/

PostType.php

class PostType extends \PostTypes\PostType
{
    // I don't know whether we'd have to introduce that many new properties.
    // It's just what I came up with for now
    public string $textdomain = '';
    public string $textdomainDir;
    public string $textdomainFile;
    public static $defaultTextdomain = 'PostTypes/PostType';

    public function textdomain($textdomain, $textdomainDir, $textdomainFile = '')
    {
        $this->textdomain = $textdomain;
        $this->textdomainDir = $textdomainDir;
        $this->textdomainFile = $textdomainFile ?: get_locale() . '.mo';

        return $this;
    }

    public function register()
    {
        add_action('init', [$this, 'loadTextdomain']);
        parent::register();
    }

    public function loadTextdomain()
    {
        // loading the default textdomain loads all the string below in "createLabels".
        // we'd have to add the translations to the project then to provide those as translated defaults
        load_textdomain(self::$defaultTextdomain, dirname(__DIR__) . '/languages/' . get_locale() . '.mo');

        if (! empty($this->textdomain)) {
            load_textdomain($this->textdomain, trailingslashit($this->textdomainDir) . $this->textdomainFile);
        }
    }

    public function createLabels()
    {
        // the singular and plural names have to be translated by the plugin's author but
        // we can provide default translations for "Add New" and the other labels if we use sprintf
        return array_replace_recursive([
            'name'               => __($this->plural, $this->textdomain),
            'singular_name'      => __($this->singular, $this->textdomain),
            'menu_name'          => __($this->plural, $this->textdomain),
            'all_items'          => __($this->plural, $this->textdomain),
            'add_new'            => __('Add New', self::$defaultTextdomain),
            'add_new_item'       => sprintf(__('Add New %s', self::$defaultTextdomain), __($this->singular, $this->textdomain)),
            'edit_item'          => sprintf(__('Edit %s', self::$defaultTextdomain), __($this->singular, $this->textdomain)),
            'new_item'           => sprintf(__('New %s', self::$defaultTextdomain), __($this->singular, $this->textdomain)),
            'view_item'          => sprintf(__('View %s', self::$defaultTextdomain), __($this->singular, $this->textdomain)),
            'search_items'       => sprintf(__('Search %s', self::$defaultTextdomain), $this->plural, $this->textdomain),
            'not_found'          => sprintf(__('No %s found', self::$defaultTextdomain), __($this->plural, $this->textdomain)),
            'not_found_in_trash' => sprintf(__('No %s found in Trash', self::$defaultTextdomain), __($this->plural, $this->textdomain)),
            'parent_item_colon'  => sprintf(__('Parent %s:', self::$defaultTextdomain), __($this->singular, $this->textdomain)),
        ], $this->labels);
    }
}

index.php

$books = (new PostType('books'))
    ->textdomain('books', dirname(__DIR__) . '/languages');

# You have to load textdomains manually before using the translation function
# so you'd have to do something like this to add a custom label with the "labels" function to translate it
# since the loading of the textdomain is done in the "register" function.
# But I guess it might as well be loaded when calling
# ->textdomain('books', ...)
$books->loadTextdomain();
$books->labels(['name' => __($books->singular, $books->textdomain)]);

$books->register();

What do you think?

Call to undefined method PostTypes\Taxonomy::register()

I would like to modify the basic category of WordPress.

I followed this part of the documentation https://github.com/jjgrainger/PostTypes#exisiting-taxonomies

     $names = [
        'name' => 'category',
        'singular' => 'Category',
        'plural' => 'Categories'
    ];

    $options = [
        'has_archive'        => false,
        'publicly_queryable' => false,
        'hierarchical' => true
    ];

    $category = new Taxonomy($names, $options);
    $category->register();

The 'register' method is not actually defined in the class

Not translating default labels

I have also noticed another thing. Without declaring any textdomains, the labels are not translated to my native language (Greek) but are in English. It doesnt trigger WordPress native language file.
Only those who are handwritten are translated.

Customize taxonomy columns

First of all, I love your class, I just updated from CTP!

Is there any way to customize taxonomy columns, as we do with custom post type?
That would be handy

Sorting broken when column key and orderby column do not match

I have added a new column event_date to an Event CPT and I want to sort on that column. The actual "event date" can be either a single day (start_date) or a range with a start and and end date (end_date). I want the column to be sortable by the "event date" so I setup the sort to use the underlying start_date according to the documentation:

$events->columns()->sortable([
	'event_date' => [ 'start_date', $sort_number ],
]);

This adds the column to the admin interface and makes it sortable and WordPress (5.2.3) sets the orderby query param to start_date which is the actual underlying post meta field that I want to sort by.

I'm encountering an issue in the setSortableColumn function of the PostTypes\PostType class. In that function, it checks if the orderby param (start_date in my case) is setup as a sortable column. This check fails because my "sortable column" is event_date and the DB query never gets modified to actually implement the sort.

Error in log when deleting or saving CPT with CPT taxonomies

[11-Dec-2021 12:33:41 UTC] PHP Warning: in_array() expects parameter 2 to be array, null given in /public/wp-content/plugins/bgi-plugin/vendor/jjgrainger/posttypes/src/Taxonomy.php on line 360
[11-Dec-2021 12:33:41 UTC] PHP Stack trace:
[11-Dec-2021 12:33:41 UTC] PHP 1. {main}() /public/wp-admin/admin-ajax.php:0
[11-Dec-2021 12:33:41 UTC] PHP 2. do_action() /public/wp-admin/admin-ajax.php:187
[11-Dec-2021 12:33:41 UTC] PHP 3. WP_Hook->do_action() /public/wp-includes/plugin.php:470
[11-Dec-2021 12:33:41 UTC] PHP 4. WP_Hook->apply_filters() /public/wp-includes/class-wp-hook.php:327
[11-Dec-2021 12:33:41 UTC] PHP 5. WPSweep->ajax_sweep() /public/wp-includes/class-wp-hook.php:303
[11-Dec-2021 12:33:41 UTC] PHP 6. WPSweep->sweep() /public/wp-content/plugins/wp-sweep/wp-sweep.php:233
[11-Dec-2021 12:33:41 UTC] PHP 7. wp_remove_object_terms() /public/wp-content/plugins/wp-sweep/wp-sweep.php:703
[11-Dec-2021 12:33:41 UTC] PHP 8. wp_update_term_count() /public/wp-includes/taxonomy.php:2901
[11-Dec-2021 12:33:41 UTC] PHP 9. wp_update_term_count_now() /public/wp-includes/taxonomy.php:3380
[11-Dec-2021 12:33:41 UTC] PHP 10. _wc_term_recount() /public/wp-includes/taxonomy.php:3397
[11-Dec-2021 12:33:41 UTC] PHP 11. get_term_by() /public/wp-content/plugins/woocommerce/includes/wc-term-functions.php:451
[11-Dec-2021 12:33:41 UTC] PHP 12. get_terms() /public/wp-includes/taxonomy.php:1062
[11-Dec-2021 12:33:41 UTC] PHP 13. WP_Term_Query->query() /public/wp-includes/taxonomy.php:1275
[11-Dec-2021 12:33:41 UTC] PHP 14. WP_Term_Query->get_terms() /public/wp-includes/class-wp-term-query.php:301
[11-Dec-2021 12:33:41 UTC] PHP 15. WP_Term_Query->parse_query() /public/wp-includes/class-wp-term-query.php:344
[11-Dec-2021 12:33:41 UTC] PHP 16. do_action() /public/wp-includes/class-wp-term-query.php:284
[11-Dec-2021 12:33:41 UTC] PHP 17. WP_Hook->do_action() /public/wp-includes/plugin.php:470
[11-Dec-2021 12:33:41 UTC] PHP 18. WP_Hook->apply_filters() /public/wp-includes/class-wp-hook.php:327
[11-Dec-2021 12:33:41 UTC] PHP 19. PostTypes\Taxonomy->sortSortableColumns() /public/wp-includes/class-wp-hook.php:303
[11-Dec-2021 12:33:41 UTC] PHP 20. in_array() /public/wp-content/plugins/bgi-plugin/vendor/jjgrainger/posttypes/src/Taxonomy.php:360

Composer

Hello
was wondering whether this could also be installed without having to install composer?

Modify existing taxonomies using Taxonomy class

Currently, the Taxonomy class will not run register_taxonomy if the taxonomy already exists (line 189). Therefore, a taxonomy cannot be modified using the class.

Will need to investigate a way to

  • Allow the class to modify a taxonomy
  • Use existing arguments over defaults if taxonomy exists (see StackOverflow answer)
  • Register changes later in order to overide existing taxonomy

Column sorting is not working for me

I was wondering whether anybody else has some issues with sorting columns - when clicking on the column that is supposed to sort I get no posts showing up at all - no error message, nothing

don't really know how to debug this.

hope somebody can help

Create custom actions

Provide the ability to create custom bulk and row actions with PostTypes. An example of the API could be as follows, but needs further exploration.

// Create a basic event post type.
$event = new PostType('event');

// Create a 'Cancel Event' Bulk Actions
$event->actions()->bulk(
    'cancel-event',     // The unique action name.
    __('Cancel Event'), // The action label.
    function($redirect_url, $action, $post_ids) { // Callback to handle the bulk action request.
        // Do stuff
        return $redirect_url;
    },
    'upload_files' // Optional: Set the capability required to use the bulk action.
);

PHP Fatal error: Uncaught TypeError: in_array() - Follow up

the error in taxonomy.php on line 361 causes another issue with the HappyFiles plugin (https://happyfiles.io) - I'm unable to create a new folder using HappyFiles in PHP 8 - it work with PHP 7

I tried to fix it like this - HappyFiles works now but I don't know yet whether this causes another issue
// don't modify the query if we're not in the post type admin if (!is_admin() || !in_array($this->name, (array) $query->query_vars['taxonomy'])) { return; }

Feature request: use Extended CPTs library

Feature request: Would you consider using John Blackbourn's Extended CPTs library as the core for your PostTypes library? Perhaps in your next major release.

The main appeal of using PostTypes is the ease-of-use and weak coupling with the WordPress hooks/filters system. Just write new PostType('new_post_type') in the global scope and the library takes care of the rest. It allows working with WordPress post types in a more object oriented/abstract fashion.
.
Extended CPT's still requires users of the library to hook into WordPress themselves, however the integration/edge-case handling is more robust than how jjgrainger/PostTypes handles things at the moment. The author is a WordPress core maintainer so his Extended library is very stable.

I think PostTypes (and the related interfaces - Columns, etc.) can be easily converted to wrapper classes for Extended-CPTs (or even as extension classes - tho that might be a bit tougher to maintain properly). The API can remain unchanged to a large degree.

Custom Post not showing in wordpress search.

I have registered my post type as follows and would expect to see it display in the standard search loop.

$recipes = new PostType([ 'name' => 'recipes', 'singular' => 'Recipe', 'plural' => 'Recipes', 'slug' => 'recipes', ], [ 'supports' => ['title', 'excerpt', 'revisions', 'thumbnail'], 'has_archive' => true, 'menu_icon' => 'dashicons-carrot', 'public' => true, 'publicly_queryable' => true, 'exclude_from_search' => false, 'capability_type' => 'post', 'query_var' => true, 'show_in_menu' => true ]);

Unfortunately, when I search for one of my recipes it doesn't show in my list. All other post types are showing. Is this a bug you have run into before?

Error with addTaxonomies

After the 1.1 update I'm seeing errors on the page now.

Notice: Undefined property: PostTypes\PostType::$addTaxonomies in /vendor/jjgrainger/posttypes/src/PostType.php on line 351

Warning: Invalid argument supplied for foreach() in /vendor/jjgrainger/posttypes/src/PostType.php on line 351

Looks like the variable $newTaxonomies was changed to $addTaxonomies and wasn't updated on line 72.

Internationalize the dropdown list of taxonomies

Hi @jjgrainger

Firstly, thank you for this small library that really helps to simplify the code of my WordPress plugins !

The issue I'm pointing out is that the default label of the dropdown list of taxonomies is currently hard-coded with an English prefix Show all {taxonomy label}. The problem is that I mainly code websites in other languages so I need to translate it. I would suggest removing the prefix or surround it with a translation method so that we can translate it ?

Small preview of the issue :
dropdown

Best regards.

Incorrect property types in PostTypes class PHP doc

Hi,

Currently a number of the properties in the PostTypes class have an incorrect type declared for them. $name, $singular, $plural, $slug are all declared as arrays but I believe they should be strings?

Cannot modify existing post types

As described in your docs here, it states that you can modify built in PTs using this package.

But in the PostType class, we encounter the following code which clearly makes this impossible:

public function registerPostType()
{
    // create options for the PostType
    $options = $this->createOptions();

    // check that the post type doesn't already exist
    if (!post_type_exists($this->name)) {
        // register the post type
        register_post_type($this->name, $options);
    }
}

It would be great if this could work again! Until it does, could you please remove it from the docs.


I tried using register_post_type_args to modify the post built in, but to no real luck - the post types are initially declared in wp-settings@347, which is before functions.php has been loaded.

I know we can modify built-ins through entirely different means such as modifying the global $wp_post_types, but that's all I got

Support PostTypes

hello
I was wondering whether this plugin is still fully supported or whether development has kind of stopped - is is still save to use this plugin??

Add function_exists checks to WP functions

When using composer's autoloader, it fails because any WordPress function isn't found. I'd like to add function_exists checks to any method that includes a WordPress functions to resolve this issue.

NOTE: In my case, I'm also autoloading files that call PostTypes registrations. But there shouldn't be any harm in adding these checks.

PHPCS

Hi there,

Thanks for the great plugin!

I was thinking, it would be nice if you can integrate PHP CodeSniffer and lint your code against PSR2 code stylings...

Thanks,
E

Sorting not working

Hey. I have issues with sorting. I am using ACF to create custom fields. Even columns populate correctly, it has ASC sorting, even if I see &order=desc.
As for text, it doesn't order correctly.

Part of code

        $portfolio->columns()->set([
            'cb' => '<input type="checkbox" />',
            'title' => __("Title"),
            'port_tax' => __("Categories"),
            'port_tag' => __("Tags"),
            'client' => __("Client"),
            'sort_order' => __("Sort Order"),
            'date' => __("Date")
        ]);

        $portfolio->columns()->populate('client', function($column, $post_id) {
            $client=get_field('client_related',$post_id);
            echo (isset($client[0]) ? $client[0]->post_title : '');
        });

        $portfolio->columns()->populate('sort_order', function($column, $post_id) {
            $sort_order=get_post_meta($post_id,'sort_order',true);
            echo (int)(isset($sort_order) ? $sort_order : 999999999999);
        });

        $portfolio->columns()->sortable([
            'sort_order' => ['sort_order', true],
            'client' => ['client', false],
        ]);

use PostTypes\Taxonomy is missing in Examples

Hi,
first of all I need to say that this project is awesome! The same holds for your documentation!
I just testet your example today and it seens like a little import for Taxonomies is missing. So I would suggest to change two lines in the README.md and the examples/books.php:

// Import PostTypes.
use PostTypes\PostType;

to

// Import PostTypes and Taxonomies.
use PostTypes\{PostType,Taxonomy};

Or am I missing something?

Taxonomy not displaying

/**
 * Register `team` post type
 */

use PostTypes\PostType;
use PostTypes\Columns;
use PostTypes\Taxonomy;


$author_names = [
    'name' => 'author',
    'singular' => 'Author',
    'plural' => 'Authors',
    'slug' => 'book-authors'
];

$options = [
    'has_archive' => false,
    'supports' => array('title', 'editor', 'thumbnail', 'excerpt')
];

$author_labels = [
    'featured_image' => __( 'Author Image' ),
    'add_new_item' => __('Add new Author')
];

$authors = new PostType($author_names, $options, $author_labels);
$authors->icon('dashicons-admin-users');
$authors->register();
$authors->flush();

//Taxonomies
$taxonomy_names = [
    'name' => 'book',
    'singular' => 'Book',
    'plural' => 'Books',
    'slug' => 'Books'
];
$options_taxonomy = [
    'hierarchical' => false,
];

$book_taxonomy = new Taxonomy($taxonomy_names, $options_taxonomy);
$book_taxonomy->register();

This is the current code i have on my theme, am i missing anything to make the taxonomy work?

WP Coding standards

Not really a bug, but shouldn't the whole PHP code follow strict WP Coding Standards too?

@jjgrainger Obviously feel free to just close this off if you prefer to keep your style, this is more of a suggestion, as it's a pure WordPress project.

populate column for taxonomy not working

hello
got the following code:

`$cats = new Taxonomy( $names, $options );
$cats->posttype( 'gear' );

$cats->columns()->add( array(
	'pid' => __( 'ID' ),
) );

$cats->columns()->populate( 'pid', function ( $column, $post_id ) {
	
	var_dump($post_id); // this shows 'pid' instead of the $post_id
} );

$cats->columns()->order( array(
	'pid' => 1
) );`

trying to populate the pid column with the taxonomy ID but $post_id returns 'pid'??

what am I missing??

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.