diceline-chartmagnifiermouse-upquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

How To Change The Slug of A Custom Post Type in WordPress

To change the slug for a post type in WordPress, you can use the register_post_type() function. Within the arguments array for the function, you can set the rewrite parameter to an array with the new slug you want to use.

Here's an example code snippet:

function change_post_type_slug() {
    $args = array(
        'rewrite' => array( 'slug' => 'new-slug' ),
        // other post type arguments
    );
    register_post_type( 'your_post_type', $args );
}
add_action( 'init', 'change_post_type_slug' );

In this example, replace your_post_type with the name of the post type you want to change, and replace new-slug with the new slug you want to use.

Once you've added this code to your functions.php file, you'll need to go to Settings > Permalinks in the WordPress admin dashboard and click the "Save Changes" button to update your permalinks. This will ensure that your new slug is properly applied.

How to Configure Traefik to Use Existing TLS Certificates

  1. Create a new file tls.yml
tls:
  stores:
    default:
      defaultCertificate:
        certFile: /etc/traefik/certs/your-domain.dev/cert.pem
        keyFile: /etc/traefik/certs/your-domain.dev/privkey.pem
  1. Make sure you're copying this file in your Dockerfile

COPY .docker/traefik/conf.d/tls.yml /etc/traefik/tls.yml

  1. Mount the certs folder in your docker-compose.yml file
volumes:
  ...
	- .docker/traefik/certs:/etc/traefik/certs
  ...
  1. Update the traefik.yml config to support the file provider:
providers:
		...
    file:
      filename: "/etc/traefik/tls.yml
    ...

How To Keep Your Github Actions Workflows Private in an Open Source Repository

If you want to make your repository open source, but keep the workflows private, you can do the following:

  1. Create a separate repository for your workflows and make it private.
  2. In the open source repository, include only the necessary configuration files (e.g. .github/actions) and reference the private repository as a submodule.
  3. In the private repository, configure the GitHub Actions workflows as you normally would.
  4. When someone clones or forks the open source repository, the submodule reference to the private repository will not be included.

This way, you can keep your workflows private, while still making your repository open source.

Meteor.js powered React hook for retrieving articles with error and loading state handling

The custom hook created uses Meteor's useTracker hook and the subscribe method to subscribe to the article publication, as well as the ArticlesCollection to find the article with the matching _id (which is the same as the slug in this case).

const useArticle = (slug: string): any => {
    const [error, setError] = useState<Error | null>(null)

    return useTracker(() => {
        const sub = Meteor.subscribe('article', { _id: slug })
        if (sub.ready()) {
            const article = ArticlesCollection.findOne({ _id: slug })
            if (article) {
                return {
                    loading: false,
                    error: null,
                    article,
                }
            } else {
                setError(new Error(`Article with slug "${slug}" not found`))
                return {
                    loading: false,
                    error,
                    article: undefined,
                }
            }
        } else {
            return {
                loading: true,
                error: null,
                article: undefined,
            }
        }
    }, [slug, setError])
}

This hook can be used in a React component to display the article, its loading state and error:

const Article = ({ slug }: { slug: string }) => {
    const { loading, error, article } = useArticle(slug)

    if (loading) {
        return <div>Loading...</div>
    }

    if (error) {
        return <div>Error: {error.message}</div>
    }

    return (
        <div>
            <h1>{article.title}</h1>
            <p>{article.body}</p>
        </div>
    )
}

Eager Loading with Subqueries in Laravel Eloquent

Eager loading with subqueries allows you to load related models using a subquery instead of joining the tables, which can improve performance in certain situations. For example, if you have a User model and a Post model, you can count the number of posts created by each user in the last month using a subquery like this:

$users = User::withCount(['posts as post_count' => function ($query) {
    $query->select(DB::raw('count(*)'))
          ->where('created_at', '>', now()->subMonth());
}])->get();

Laravel Request Authorization: Understanding the Differences between Request Classes and Policies

In Laravel, both request classes and policies can handle authorization.

Request classes have an authorize method that is called automatically by the framework before the request is handled. It is a convenient way to perform authorization checks on a specific request.

Policies provide a more flexible and reusable way to handle authorization across multiple request classes. They are classes that organize authorization logic around a particular model or resource. They allow you to define granular abilities for your application's users and groups.

When both the request's authorize method and a policy's __call method (or method with the same name as the action) return false for the same action, the framework will consider the user as unauthorized and will return a 403 Forbidden response.

In such scenarios, the priority is given to the authorize method of the request class. If it returns true, the framework will continue to process the request and will not check against any policy. However, if it returns false or throws an exception, Laravel will check the policy's method with the same name as the action, and if it returns false, the user will be considered unauthorized and a 403 Forbidden response will be returned.

In summary, both request classes and policies can handle authorization in Laravel, with priority given to the authorize method of request classes.

Matching dates within a monthly Interval that crosses over multiple years with PHP and Carbon

function getDatesInRange($dates, $start, $end) {
    $datesInRange = $dates->filter(function ($date) use ($start, $end) {
        if ((int) $start->format('Y') === (int) $end->format('Y')) {
            $start->year((int)$date->format('Y'));
            $end-> year((int)$date->format('Y'));
        } elseif ((int) $start->format('Y') < (int) $end->format('Y')) {
            if ((int) $date->format('m') >= (int) $start->format('m')) {
                $start->year((int) $date->format('Y'));
                $end->year((int) $date->format('Y'))->addYears(1);
            } else {
                $end->year((int) $date->format('Y'));
                $start->year((int) $date->format('Y'))->subYears(1);
            }
        }

        return Carbon::parse($date)->isBetween($start, $end);
    });

    return $datesInRange;
}

How to optimize the performance of the map function in JavaScript

To optimize the performance of a map function in JavaScript, you can do a few things:

  1. Use the forEach method instead of map if you are not creating a new array from the iteration. forEach is faster because it does not create a new array.

  2. Use the map method on a smaller array if possible. For example, if you have a large array and you only need to map over a subset of it, create a new array with just the subset and use map on that.

  3. If you are using map to transform each element of the array, use a specialized method for the transformation instead of using map. For example, if you are transforming each element to a string, use the toString method instead of using map.

  4. If you are using map to filter an array, use the filter method instead. filter is optimized for filtering and will be faster than using map for that purpose.

  5. Use a for loop instead of map if you need to perform complex operations on each element of the array. map is optimized for simple transformations, so a for loop will be faster for more complex operations.

Redirect unauthenticated users with meteor.js and react-router 6

The challenge I encountered was accessing the Meteor.user() in React Router's route loader property.

Alternatively, instead of querying the server, I'm picking up the user id from localStorage. The absence of it indicates the user is logged off or never logged in. Until Meteor kicks off, no sensitive data is displayed anyway.

...
{
  path: '/',
  element: <App />,
  errorElement: <ErrorPage />,
  loader: async () => window.localStorage.getItem('Meteor.userId'),
}
...

and in app.tsx:

const userId: UserId | null = useLoaderData()
const navigate = useNavigate()

useEffect(() => {
  if (userId === null) navigate('/login')
}, [userId])