Domanda

I want to have ability to choose for each page what post should appear in a sidebar, from multiple posts type. So I understand that I need a meta box with a dropdown list of all posts, but I don't know how to build this in functions.

I only found this solution which is quite similar to what I want, but this doesn't help me to much, because I can only choose from a single post type and display only in post pages.

È stato utile?

Soluzione

There is a free plugin that will solve all of your woes. It's called ACF or Advanced Custom Fields. It has the ability to add a list of posts to a field and attach that field to pages. Here's how you'd do it:

First install the plugin and navigate to the custom fields screen. Setup your field exactly like this:

ACF screenshot of posts

Then in the options below that section you need to select these options:

ACF page options

That will tell ACF to put the field only on pages. After you have set that up you will get a little sidebar block like this:

enter image description here

You can then select each post for the page and it will return that object on the frontend. You do need to use a little code to get the frontend to spit out the posts you need. Here is the code to get a frontend option from ACF. Inside of the sidebar.php file you need to add this code:

global $post; // Get the global post object

$sidebar_posts = get_field('posts', $post->ID); // Get the field using the post ID

foreach($sidebar_posts as $sidebar_post){ // Loop through posts
    echo $sidebar_post->post_title; // Echo the post title
}

This will simply loop through the posts you select and echo out the title. You can do more with this by adding some other Wordpress post functions using setup_postdata(). This will allow you to do things like the_title() and the_content().

Hope this helps!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top