INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Wordpress custom styles in menu page I have added a menu page to my plugin. In the wp codex is described that I can use a seperate .php file for the content of the menu. function register_custom_menu_page() { add_menu_page('custom menu title', 'custom menu', 'add_users', 'myplugin/myplugin-index.php', '', plugins_url('myplugin/images/icon.png'), 6); } myplugin-index.php <?php echo "Admin Page Test"; ?> Now I want to use custom styles (.css) in the myplugin-index.php. How can this be achieved? BR, mybecks
You could use <!doctype html> <head> <style type="text/css"> #toplevel_page_custom_menu_title{ display:none !important; } .update-nag{ height:auto !important; } </style> </head> <body> <div class="update-nag"> <?php echo "Admin Page Test"; ?> </div> </body> </html> You can enqueue this way function prefix_add_my_stylesheet() { wp_register_style( 'prefix-style', plugins_url('style.css', __FILE__) ); wp_enqueue_style( 'prefix-style' ); } add_action( 'admin_enqueue_scripts', 'prefix_add_my_stylesheet' ); Reference: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "css, plugins" }
Retrive posts thumbnail in original size Hi I am trying to integrate a jquery gallery into my wordpress theme.The gallery will have a caption that will display the posts title and excerpt content. What I am thinking to do is create a custom query for the posts and retrieve the posts thumbnail image aldo I would like to be able to get the image in it's full size that is stored in the media gallery. Is there a way I can achive this?
Try this: <?php echo get_the_post_thumbnail($page->ID, 'full'); ?> codex.wordpress.org/Function_Reference/get_the_post_thumbnail#thumbnail
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
Plugin to send messages to members/lists but not full-blown newsletters I'm looking for a plugin that would allow the owner of a school to send student members short email messages. We don't need a full-blown newsletter feature but it does need to be able to have multiple lists (kids classes, adult classes, etc). Users don't need to talk to each other, just get a message that, for instance, the 10am class is cancelled, etc. Something like mailchimp seems like overkill and too much work for the client. Ideas? Thanks!
A quick google turned up this post - How to Email Subscribers from WordPress Which recommended ... > Email Users is probably the simplest email plugin, and seems to do the job. It picked up my existing subscribers from the database and sent an email. It does exactly what it’s supposed to do.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, email, lists" }
Force User Login Surprised I haven't found this Q. I want to force users to login to the site before accessing any of the content. I have this function: function av_force_user_login() { global $post; global $pagenow; if ( in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ) ) { return; }else{ auth_redirect(); } } add_action( 'get_header', 'av_force_user_login' ); This doesn't seem to work though and after I try and login I get redirected back to the login page. One caveats to watch out for (in my case): I'm using BuddyPress' registration system which doesn't apply to the login page but it would apply to the `wp-login.php?action=register` page which redirects to Buddypress' template for registration. Nevertheless, is there anything wrong with the above code that would cause a redirect back to the login page?
Very Basic Script. This should work. add_action('template_redirect', 'redirect_to_login'); function redirect_to_login(){ if(!is_user_logged_in()){ // user not logged in so redirect them to login page $redirect_url = '' // you can determine where to redirect user after they login wp_redirect( wp_login_url($redirect_url), 301 ); exit; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, login" }
How to implement a secondary menu? I actually need to implement a secondary vertical menu like in here: < It has to be vertical and it looks like it based on frames, but as I know frames are obsolete, so how should I do this? Is there a plugin for this?
It sounds like you're looking for a sub-menu for the current menu item from another menu - if that makes sense itself ;) One that I've personally used with great success is Advanced Menu Widget. Tons of options and does exactly what you want. Thanks! Features include: * Custom hierarchy - "Only related sub-items" or "Only strictly related sub-items". * Starting depth and maximum level to display + flat display. * Display all menu items starting with the selected one. * Display only direct path to current element or only children of selected item (option to include the parent item). * Custom class for a widget block. * And almost all the parameters for the wp_nav_menu function.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
Get current post featured image ID Is it possible to retreive the current post (inside the loop) featured image ID? The reason why I want this is so I can do something like this... <?php $featuredID = //get the featured image id echo do_shortcode('[gallery size="thumbnail" link="file" exclude="' . $featuredID . '"]'); ?> Any help would be great thanks!
Sounds like you're looking for `get_post_thumbnail_id()`: $featuredID = get_post_thumbnail_id(); It returns `null` if there's not a featured image, so you may want to add a check for that.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 0, "tags": "post thumbnails" }
How to control who can view certain pages in BuddyPress? I would like to control who can see a page in BuddyPress and restrict anyone else from accessing it. Something along the lines of the following pseudocode: <?php if ( loggedin_user_ids==1,4,5,7 ) { ?> // Show page <?php } else { ?> // "You are not allowed to view this page" message <?php } ?> So basically, I need: 1. To be able to **control who can see the page** , not just any logged in user. 2. I also need to **control which pages this applies to** , not just any page. I am new to BuddyPress so I don't know **which functions and variables to use** here. I imagine something like this could be done in the template files, or maybe in the _bp-custom.php_ file. **Or is there a better solution to this?**
> I am new to BuddyPress so I don't know which functions and variables to use here. Read the codex - for example: < You could create a function in your theme- functions.php or in bp-custom.php and call it from template files and pass it parameters like allowed_users, etc. Or you code hard-code something like this into specific template files. global $bp; $allowed_users_array = (1,4,5,7); if (in_array($bp->loggedin_user->id, $allowed_users_array)) { // Show page } else { // "You are not allowed to view this page" message // or load a custom error page using locate_template( array( 'some.php' ), true ); // or redirect somewhere by using bp_core_redirect( ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, buddypress, security, private, privacy" }
How can I prevent posts with no title showing up in my query? How do I prevent posts with no title showing up in my query / loop ? ( I am doing aside, quote etc post-formats and I want to exclude title less posts from one particular loop) I have nothing on this. I searched through `WP_Query` on this but I can't find anything, and when I try google everything is muddied with 'not display title stuff' etc. Is it possible?
Please find below a quick solution to your problem 1. first query for all empty titles 2. place the result in an array 3. query again for post__not_in see below sample code $query = new WP_Query('post_title=\'\''); $a_empty_titles = array(); while($query->have_posts()){ $query->the_post(); array_push( $a_empty_titles ,$query->post->ID); } wp_reset_postdata(); wp_reset_query(); echo count($a_empty_titles); $query = new WP_Query( array( 'post__not_in' => $a_empty_titles ) ); //your loop code here //reset query wp_reset_postdata(); wp_reset_query(); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, wp query, loop, post formats" }
Which is better: 301 Redirect in my .htaccess file or a plugin like Redirection? Currently I am using 301 Redirects in my .htacess file to redirect old URLs to new URLs. Are there any performance benefits (i.e. site loading) o using a plugin like Redirection or should I just stick to hardcoded 301 Redirects?
The `.htaccess` catches requests before WordPress is even started. That’s _much_ faster than any plugin. For a handful of redirects I wouldn’t install a plugin. You need that only in cases when the server cannot know the new address, for example if you rename permalinks (slugs) automatically (you shouldn’t ;)).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "htaccess, redirect" }
Attachment Image using wrong src? I've had some issues recently with this code below to display the featured image of a page: add_theme_support( 'post-thumbnails' ); add_image_size("homepageFeatured", 250, 250, false); wp_attachment_image(get_post_thumbnail_id($post->ID), 'homepageFeatured'); //in the loop The issue is that it's pulling a 150x150 image (the 250x250 does exist, and the url is accessible, I used the Thumbnail Regenerator plugin) and then resizing that up to 250x250 (causing to to be blurry). Any ideas on why this is occurring? Thanks, Max
Are you just trying to display the post thumbnail in the homepageFeatured size? if so, try: echo get_the_post_thumbnail($post->ID, 'homepageFeatured'); In your loop.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails, images" }
One post carries 30 postmeta values, is this too much? I have some data saved as post meta, occasionally some plugins may save an extra piece. Now I installed bbpress, it saves at least 10 pieces of post meta. Adding them together, there are nearly 35 pieces of post meta per post. I think WordPress can handle much more if without bbpress. **With bbpress forum, the number of posts will increase dramatically, multiply by the number of post meta, it will be a huge post meta table**. Will it be a problem?
No, to be honest 35 is nothing. You should not see any problems scaling this into the hundreds/thousands if optimized right, it does depend on many factors. Where is the post meta being used, are you sure it's all being used? Are you using a lot of unique keys? You can check this by doing `get_post_custom_keys`, the lower the better. Are you outputting all post meta in one shot using `get_post_custom` instead of getting each field via `get_post_meta` ? You should always turn on debugging with `define('SAVEQUERIES', true);` and see how many hits to the DB your doing and how long each one is taking.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "database, post meta, performance" }
A question about .htaccess I'm redeveloping a site for a client. Their current site is written in .asp. I've rebuilt in WordPress as they need a CMS. We're repointing the DNS to our hosting environment. My question is - I need to set up an .htaccess file (I think this is the best way) to redirect all the old URLs to their new equivalent. Some of the URL structures have changed so it's not just a case of changing .asp > .php. Soo... where should I upload the .htaccess file - does this need to go in the root directory OR does it need to go in my wp-theme folder? Thanks
You can just add the .htaccess to the root of the website however be cautious as WordPress will have added it's own if you have changed the link slug structure within the WordPress admin. In the htaccess file you should use 301 re-direction's like so: redirect 301 /oldpage.asp If it is a big site then you will not want to re-direct all pages although it could be worth while. I normally just do a Google site: search and re-direct the most important pages and any with first or second page listings.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, htaccess" }
Posting from Wordpress to Facebook Is there a plugin that automatically posts your blog post to Facebook? And only to a specific Page (because I'm admin of several).
WordPress plugins repository has plenty ... have you tried the Official Facebook plugin? I'd always recommend you search the plugin repository first and then come here and explain what plugins you have installed.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, facebook" }
WP_Query vs get_posts I have read a **number** of **questions** on SE regarding these but I still can't figure the exact difference wrt usage. Would it be true to say that I would probably use WP_Query for the majority of secondary loops and only use get_posts if I need the results returned in an array, or to put it another way is the main difference between the two the array vs object return, or is there some other major factor I should be aware of?
### The difference between get_posts & WP_Query You can view `get_posts()` as a slimmed down `WP_Query`. In fact looking at the source: //... prepares query array $r $get_posts = new WP_Query; return $get_posts->query($r); `get_posts()` use `WP_Query`, but only returns an array of posts - nothing more. Furthermore it sets: $r['no_found_rows'] = true; Normally (by default with `WP_Query` object) - WordPress queries how many posts there are in total - even if you are only after the first 10. It does this so it can perform pagination. So `get_posts()` is actually (slightly) quicker (it also ignores sticky posts). ### Which to use... If you only need an array of posts, and don't _need_ the query object -use `get_posts()`. Otherwise, if you do need the access to the query object methods, or pagination, or sticky posts at the top, you should use `WP_Query`.
stackexchange-wordpress
{ "answer_score": 18, "question_score": 8, "tags": "wp query, loop, query posts, query, get posts" }
Is there any need to use both wp_reset_postdata and wp_reset_query together? Is there any need to use both `wp_reset_postdata()` and `wp_reset_query()` together? Is it a case that I would pick one of the two functions; is there any point in doing this after a query : wp_reset_postdata(); wp_reset_query();
There's no need to use them both. You should only use `wp_reset_query()`, if you modified query with `query_posts()` (which you should avoid). This function also call `wp_reset_postdata()` \- < So it's better to use `wp_reset_postdata()` after running separate query.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "theme development, loop, query, reset, wp reset postdata" }
Get the number of rows from $wpdb->get_results not working I want to count the number of rows of this custom wordpress query and it does not work: *PS I am accessing a custom table inside my wordpress database, mabe by myself. The $wpdb->get_results part works.* $myquery = $wpdb->get_results("SELECT COUNT(*) FROM `$table` WHERE $myconditions"); $nr = $myquery->num_rows; Any ideas why? Important: using $wpdb->get_results like this: * Do I need to prepare the query (i read it in the codex)? * Do I need to somehow reset the query after I have used it? Ty for helping!
Doing a Select Count(*) ... will only ever output one row with a single value - the number of rows that satisfied your where clause.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, query" }
Is it necessary to reset the query after using get_posts()? Is it necessary to reset the query after using `get_posts()` ? I have been looking at this page and I don't see any reference to `get_posts()` ... I can't make it out for sure from this page either. I can't see why it wouldn't be necessary ( though on my test page it doesnt cause any problems without `wp_reset_postsdata()` `wp_reset_query()' or ''rewind_posts()' ) but if it is which is the right function(s) to use.
No. `get_posts()` does not modify global `$wp_query` variable and it doesn't need to be cleaned up. Note that if you further use `setup_postdata()` you do need to `wp_reset_postdata()` afterwards.
stackexchange-wordpress
{ "answer_score": 30, "question_score": 11, "tags": "loop, get posts, wp reset postdata, wp reset query" }
WordPress Attachments vs Post Meta Apologies if this is not a _question_ and belongs more in discussion, but In dealing with image attachments for a portfolio site, what is the benefit to having images be "attached" to a post versus saving the image IDs as an array in a post_meta field?
The WordPress "gallery" functionality partly depends on the attachment of the media to the post via the `post_parent` column. > Specifying IDs in your shortcode allows you to include images in your gallery that aren't necessarily "attached" to your post — that is to say, not uploaded from within your post or page. This flexibility allows you to create and embed any number of galleries containing any number of images! > > Note: If you choose to just use the "barebones" version of the [gallery] shortcode in your post or page, only images that are "attached" to that post or page will be displayed. > > < You can see in the source that shortcode uses `get_children`, which has quite a comment block in the source, and again you can see that `post_parent` is a key factor. There are probably other ways to answer the questions but that is the first that comes to my mind.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "attachments, post meta" }
How is the " wp_get_update_data " function used? i need to list user **updates** from a word press powered site, like how we get list of comments and posts using `wp.getComments` and `wp.getPosts`, and i came across `wp_get_update_data` can we list user updates using this wp_get_update_data, and is there any chance to list updates using **rss**?
`wp_get_update_data()` collects and returns number of updates available for plugins, themes and WordPress core. It's used in Admin Bar and admin update menus.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, rss" }
How to properly print a 404 error without redirecton? (i.e. keeping the current URL) There are some pages on my BuddyPress install that I would like to hide by printing a 404 error. With the help of the following question: Redirect Restricted Page to 404 I came up with this code: global $wp_query; $wp_query->set_404(); status_header( 404 ); get_template_part( 404 ); exit(); Most of the page is hidden nicely and a 404 error is printed, however what has been printed before this code remains (including the header title of the page I want hidden). Unfortunately I can't move this code higher up, before anything gets printed. So is there a way to **clear everything that has been printed before** and then **print a fresh 404 error** but with **keeping the current URL**? (So no redirection to the 404.php page.)
You should be using a filter outside of your template for this: add_filter( 'template_include', 'wpa62226_template_include', 1, 1 ); function wpa62226_template_include( $template ){ if( is_page( 'some-page' ) ) : global $wp_query; $wp_query->set_404(); status_header( 404 ); $template = locate_template( '404.php' ); endif; return $template; } Your code is executed before the template is loaded, so it becomes a non-issue.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "urls, buddypress, 404 error, private, content restriction" }
Persistent sidebar.php This sidebar does not let itself be aligned either on the left or on the right, so that the content below (the posts) can be placed next to it. Sidebard on one side, posts on the other. This is the page: < And this is the index.php: <
#left { float: left; width: 40%; } It may help you but, it seriously is an HTML and formatting issue.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "sidebar, blog" }
Query for recent images across multiple posts I'm a bit fresh to wordpress theme development (and PHP in general), and I'm curious if there is a way to query XX number of recent images, likely spanning across multiple posts. Basically I want to create a widget that shows a 3x3 set of the most recent images used in posts. Any thoughts on how one would accomplish this?
You can use `get_posts` or create a new `WP_Query` using the following args (or something similar). <?php $args = array( 'post_type' => 'attachment', // attachment post type 'post_status' => 'inherit', // all attachments have this post status 'post_mime_type' => 'image', // make sure you get images only 'posts_per_page' => 5 // however many images you want ); When looping through the images, you can use `wp_get_attachment_image` or `wp_get_attachment_image_src` to grab the image HTML or image URL respectively. <?php $attachments = get_posts($args); // args from above foreach($attachments as $a) { // replace `thumbnail` with an appropriate image size echo wp_get_attachment_image($a->ID, 'thumbnail'); } You'll also want to read up the widgets API for creating widget. The codex has a basic example. There's also quite a few tutorials out there, here's one I wrote.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "images, widgets" }
Second tier sidebar navigation I'm trying to create a second level navigation in WordPress. I've found lots of examples, but none of them seem to do exactly what I want. This code below has me almost there, but I want an active class or better yet a way to only show the sub navigation if I'm on it. It would be great it WordPress had a depth_start option along with depth. Example: link1 link2 (active class) link2-1 link2-2 link2-3 link3 link4 Code so far: <?php $parent = array_reverse(get_post_ancestors($post->ID)); $first_parent = get_page($parent[0]); $args = array( 'depth' => 0, 'child_of' => $first_parent->ID, 'title_li' => __($first_parent->post_title), 'sort_column' => 'menu_order', ); ?> <nav class="sidebar"> <ul> <?php wp_list_pages( $args ); ?> </ul> </nav>
For now I have decided to use a CSS solution. I realized with the code above I do actually have classes I can work with. For example if you had this navigation in a you could use something like this. nav.sidebar li li li { display: none; } nav.sidebar li li.current_page_item > ul > li, nav.sidebar li li.current_page_ancestor > ul > li { display: block; } While not ideal, it gets the job done.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, navigation, wp list pages" }
Commas in Tag Cloud Using `<?php wp_tag_cloud(''); ?>` to display tags on my website, how do I separate each tag with a comma but also remove the comma from the last tag?
According to the Wordpress Codex on tag clouds, you need to specify a comma as the "separator" argument. $args = "separator"=>","; wp_tag_cloud($args);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, theme development, themes, tags" }
Displaying Tags for the Page I'm On? I currently have `<?php $comma = array( 'separator'=> ", " ); wp_tag_cloud($comma); ?>` and I thought this was solved, until going to other posts and seeing the same exact tags.. so I'm guessing this is displaying every tag possible. How do I only display the tags related to each post?
You can use `<?php the_tags(); ?>` in the Wordpress loop to display all tags for current post. The default separator is `,`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, tags" }
Get list of registered or enqued styles? looking for filters or actions Where can I get the list of styles about to be printed? What i want is to either filter the list, doing what i want with each, then return empty list. Or do an action that recieves the list, then i can remove_action the print_styles. Something like that, anyway. I'm creating a css minifier concatenizer.
There is a global variable named `$wp_styles`. It is a `WP_Styles` object (if it exists at all) and it holds all the enqueued styles in a public variable `$queue`. Untested: global $wp_styles; if ( is_a( $wp_styles, 'WP_Styles' ) ) { print_r( $wp_styles->queue ); } else { print 'no styles enqueued'; } Make sure you test that _after_ the `init` hook, because stylesheets should not be enqueued earlier. For details see: * `/wp-includes/functions.wp-styles.php`, * `/wp-includes/class.wp-styles.php` and * `/wp-includes/class.wp-dependencies.php`
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "css, filters, actions" }
confusion with add_filter I am trying to customize the default WordPress search field. So I thought I could add a filter to remove the function and then add in a new function with the fields the way I want them. So I tried this function savior_search(){ <form role="search" method="get" id="searchform" action="<?php echo home_url( '/'); ?>"> <input type="text" value="" name="s" id="s" /> </form> <?php } add_filter( 'get_search_form', 'savior_search'); It seems to work but for some reason that I don't understand, it duplicates the search field. It puts the form on the page twice. I also commented out get_search_form in the sidebar yet when I refresh my page, it's still there. I am using the filter incorrectly? My search function is in the functions.php.
Your syntax is wrong, you're mixing up the `html` and `php function` at the beginning. See Filter here - wp-includes/general-template.php#L151 I think we should return the form, instead of printing it, See my example, It should work, If you want to modify something, do it in function. **Example -** function savior_search(){ //Modify This $form = '<form role="search" method="get" id="searchform" action="' . esc_url( home_url( '/' ) ) . '" > <div><label class="screen-reader-text" for="s">' . __('Search for:') . '</label> <input type="text" value="' . get_search_query() . '" name="s" id="s" /> <input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" /> </div> </form>'; return $form; } add_filter( 'get_search_form', 'savior_search');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters" }
Assign a category by user and customize the edit-tags.php?taxonomy=category page I've been searching for days now without success... Here's my goal: \- assign a top level category by user (this I've made it) \- let each user create child categories only in his assigned category (this I need to do) For example: \- category-1 > user-1 \- category-2 > user-2 SO user-2 can only create sub-category in category-2... At the end it's like leaving to users the "manage_categories" capability but having it modified so that the user only create categories in its own assigned parent category. And by the way not seeing the other top level categories on the list categories page (edit-tag.php). Here I'd like to custom the edit-tags.php?taxonomy=category page depending on the user seeing it... Thanks for your time and advice. David
This is how I did it : function if_restrict_categories($categories) { global $current_user; $a = get_cat_if_user($current_user->ID); $onPostPage = (strpos($_SERVER['PHP_SELF'], 'edit-tags.php')); if (is_admin() && $onPostPage && !current_user_can('level_10')) { $size = count($categories); for ($i = 0; $i < $size; $i++) { if($categories[$i]->parent != $a && $categories[$i]->term_id != $a){ unset($categories[$i]); } } } return $categories; } add_filter('get_terms', 'if_restrict_categories'); And where `get_cat_if_user()` is a custom function where I get the category I've assigned to my user. Hopes it helps others. Cheers.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, admin, taxonomy, users, user roles" }
Form that sends data to an admin panel and can export it Is there a way to have a form submit data to a admin control panel where the data is stored and can be rectified there? Could it also be able to export the data as excel for example?
there are 2 very popular form plugins 1. Gravity Forms \- extremely customisable and saves all data to your database (Commercial) 2. Contact Form 7 \- also saves everything to your database and easy to use (Free) Both send the data to the Admin panel so you can review inside WordPress. I know that Gravity Forms has an option to EXPORT the form entries as a CSV file. **Review Form Submissions without logging in** Both can send email notifications to your email address so you can see what has been submitted without logging into WordPress. The other way to see all the form submissions without logging in is to open your SQL database and view the data there. Then you can save the table as a CSV.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "database, forms" }
Retrieve Path of admin.php Is there a better way of retrieving the path of admin.php and the url of wp-admin.css? What I can think of is: $adminphppath = ABSPATH . '\wp-admin\admin.php'; $admincssurl = get_bloginfo('wpurl') . '/wp-admin/css/wp-admin.css"; But, some may be changing the admin path for security. So I need a more reliable way. [Edit] I need the system path for admin.php, not url. Because I need to include it.
You can use `admin_url()` function for wp-admin.css file and ABSPATH for admin.php. $admin_php_path = ABSPATH . '/wp-admin/admin.php'; $admin_css_url = admin_url( 'css/wp-admin.css' );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "wp admin, paths" }
Adding Sorting to Website? I would like to add sorting but don't have any idea how ot go about it. I would like to be able to sort by: > Date, Title, Price (custom field), Comments, Views, ASC + DESC What would be the best way to do something like this?
Extending this answer for custom post type support. For a custom post type you can pass an extra parameter _(`post_type` )_ to url, example - www.example.com/?post_type=FOO&orderby=title&order=dsc **Note -** If you've specified some url rewrite for that post type then the above url will become something like this but still showing all posts of post type `FOO` with descending order by title. www.example.com/FOO/?&orderby=title&order=dsc
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sort" }
Style category link depending on category ID I want to style a link depending on its ID, for instance, if the category ID is 2, then I want the link to be pink. My theme calls the category like this: <?php if (in_array('categories', get_option('theme_postinfo2'))) { ?> <?php the_category(', ') ?> I found a way to style specific categories in **lists** by adding: li.cat-item-7 { ... } /* category ID #7, etc */ to my stylesheet, however, I cannot find a way to do the same thing to links. What type of solutions are available? Please be detailed in your reply as my coding knowledge is limited.
the basic way is to #li.cat-item-7 { color: red; } Now, change '7' to the number you want, as many times as you want and 'red' to the color you want for that category like - #li.cat-item-2 { color: pink; } #li.cat-item-8 { color: green; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories, links, css, id" }
Multiple sub directories for theme template pages I apologize if this questions has already been answered, I have a feeling I'm just not using the right terminology for my search. I'm in the process of building a base theme for my employer. One of the things we want to do with this new theme is have the option to switch from a standard template to one that's been Zurbified. The way I'd prefer to handle this is by having an admin panel checkbox. Within the theme itself we want to have 2 separate folders that contain the actual theme template files (Ex: `theme_folder/normal/page.php || theme_folder/zurb/page.php`). How would I go about properly processing this? Is there a hook/filter that allows you to specify which sub folder to use in the specific situation? From what I read its possible to have the sub directories house the template page files, < , but I'm not finding the call I need to tell Wordpress to use the specific subs.
When I want to change a specific part of template, such as header OR footer then I use conditions like this - if(is_404()) { get_header(`error`); //loads header-error.php } else { get_header(); //loads header.php } In your case, you want to load a completely different template, Now the only action hook I can imagine is - `template_redirect`, Which can be used to tell wordpress to load a different template as per conditions. **Example -** function wpse62337_zurbified() {     if ( CONDITION ) {         include (TEMPLATEPATH . '/zurb/page.php');         exit;     } }   add_action('template_redirect', 'wpse62337_zurbified');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, templates, api" }
Switch to blog and get content from that blog Anyone thinks this should not work? I can't make it work for some reason. add_action( 'wp_head', function() { switch_to_blog( $blog_id ); wp_query( 'p=' . $post_id ); }); The point is that instead of displaying whatever page I am about to display, I choose content from a different blog instead.
For other people with the same issue who don't read comments the solution was to change the hook from `wp_head` to `get_header`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "multisite, wp query" }
Page template that uses lightbox to display post images I have created a page template that displays the featured image for all posts of a certain custom post type. It uses a normal loop that is querying that specific custom post type. The thumbnails are being displayed using `<?php the_post_thumbnail('project-thumb'); ?>` I now want to use a lightbox to display the rest of the images in the post. I believe that I need to use `<?php wp_get_attachment_image_src(); ?>` For some reason I can't quite get my head around it. Can anyone point me in the right direction? Thanks in advance!
You could use WordPress’ built-in Thickbox script. Just place the following code somewhere before `wp_footer();`: add_action( 'wp_footer', 't5_thickbox_jquery' ); function t5_thickbox_jquery() { ?> <script> jQuery( 'a img.size-medium, a img.attachment-thumbnail' ) .parent() .addClass( 'thickbox' ) .attr( 'rel', 'page' ); </script> <?php add_thickbox(); } See this answer for more details.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, functions" }
Clean database from unused tables I used to have many plugins installed on one of my sites, and after deleting most of them, I still have a database full of extra tables, I am sure most of them are unused. How do I clean them off?
Backup your Database and then use DROP statements to delete the tables manually via tools such as MySQL Workbench, or MySQL Query Bench. There are many alternatives you can use that provide GUIs for backuping up, restoring, and modifying DBs. Here's the WordPress DB schema, do not delete any of these tables: < Aside from that, those tables should have no impact on your site at the moment, so long as the plugins are disabled there should be no slowdown TLDR: Backup DB, delete things, see what breaks, restore if broken
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "database" }
Include Custom Posts Type in Year/Month/Date Archive I am looking for solution where I able to get all custom post types in year, month and date archive list. So it can be filters by anything either year, month or date. I am looking for function something like below which I am using to include CPT for authors function custom_post_author_archive($query) { if ($query->is_author) $query->set( 'post_type', array('wp_plugin_review', 'png_gallery', 'post', 'news') ); remove_action( 'pre_get_posts', 'custom_post_author_archive' ); } add_action('pre_get_posts', 'custom_post_author_archive');
Your code simply adds post types to the query when on the author archive so to do the same with date archive simply replace `is_author` to `is_date` : function custom_post_date_archive($query) { if ($query->is_date) $query->set( 'post_type', array('wp_plugin_review', 'png_gallery', 'post', 'news') ); remove_action( 'pre_get_posts', 'custom_post_author_archive' ); } add_action('pre_get_posts', 'custom_post_date_archive');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, archives" }
How to get a custom page through plugin? I am developing a Wordpress plugin handling a calender in which it is possible to sign up for a given event. As part of this, I want to make a custom page for the signup-form and confirmation message to the client, however I have no idea how to do this. I have seen that there is a wp_insert_post() function to insert a new post, but I need a page with custom plgin content (signup form) instead. Is this even possible to do and how do I do this if it is? Thanks
You can use `wp_insert_post` for creating the page. <?php $content = '<Sign up form content>'; wp_insert_post(array( 'post_title' => 'My page', 'post_content' => $content, 'post_type' => 'page', //VERY IMPORTANT 'post_status' => 'publish/draft' )); Check it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development" }
How to store meta field values I would like to store a few extra details for my custom post type, using meta boxes. Should I store all the values under one meta key in an array, or create several meta key and value pairs?
If you want to use the values to sort or filter the data, you should keep them as separate entries.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, metabox" }
Wordpress error when sending comment I'm using the default comments template. When I send a comment I get the following error message: **Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'wp_set_comment_cookies' not found or invalid function name in /home/mattator/public_html/wp-includes/plugin.php on line 403** **Warning: Cannot modify header information - headers already sent by (output started at /home/mattator/public_html/wp-includes/plugin.php:403) in /home/mattator/public_html/wp-includes/pluggable.php on line 881** couldn't find a call to the funciton 'wp_set_comment_cookies' anywhere in the code. It is noteworthy that despite the error message the comment is being sent properly. Any ideas would be appreciated.
Well, I experimented a little bit, and as turns out the problem was a call to the function "nocache_headers()", in Line 18 of the file "wp-comments-post.php" which lies at WP root directory. I deleted it, and voila, everything works. Not sure why though.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments" }
Use Metabox to enter Post Title I would like to use a custom meta box to build the UI for the post title, instead of the usual field 'title' supplied on WordPress post screens. I've build the meta box, the question is now how to save that field as the post_title. Anyone has done this before?
Is it really necessary to override default Wordpress title filed? instead I'd recommend using a different meta key such as - `my_the_title` to store the title into database. And then use wordpress function - `get_post_meta()` to show it, instead of `the_title()` function.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, metabox" }
Changing document title only on a custom page template Hi can anyone help with the below, please? I want to be able to change the contents of my HTML `<title>` tag only, so need to write an if / else statement. I'm getting myself a bit muddled as my PHP isn't great... but basically something along the lines of the below but combined... <?php if ( ! is_page_template('boatDetails.php') ) { ?> <title><?php bloginfo('name'); ?><?php wp_title('|'); ?></title> <?php } ?> <?php if ( is_page_template('boatDetails.php') ) { ?> <title>I'm the boat details page</title> <?php } ?> Thanks :)
I think you will want to use the `wp_title` filter. Add the following to `functions.php`: function wpse62415_filter_wp_title( $title ) { // Return a custom document title for // the boat details custom page template if ( is_page_template( 'boatDetails.php' ) ) { return 'I\'m the boat details page'; } // Otherwise, don't modify the document title return $title; } add_filter( 'wp_title', 'wpse62415_filter_wp_title' ); Make no other changes anywhere, including in `header.php`.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "filters, page template, title" }
Categories: A Greenhorn Question on Strategy (Not Code) Im having an issue in my category set-up logic Let's say I sell new/used (including Vintage) Drums/Drum Parts wherein a user can search by new, used or by individual part. So let's say they choose to search by individual part on Cymbals. The search results page should then display a listing of Cymbals should also be grouped by new/used? Right? So, in setting up my categories I'm coming up with this ## New * Drum Sets * Cymbals * Toms ## Used * Drum Sets * Cymbals * Toms But this seems redundant to me. Can I not achieve my objective WITHOUT all this duplication? So before I go hacking away at this I thought I would get a few pointers from my peers. Please advise.
you can achieve the same with out the duplication in two ways: * create a custom taxonomy for condition (new,used) * use a custom field for condition (new,used) both ways you only need to create each category only once and filter by condition.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "categories, tags, development strategy" }
displaying meta key value with wp_page_menu I know that WP3 offers wp_nav_menu and description field but I was wondering if it is possible to alter wp_page_menu to echo desired meta key value next to the page link in format that is adjustable. Hope my question is clear. Thanks
There is no easy way to alter the vale of each li in the `wp_page_menu` but there is a way to do it without creating your own function or custom walker using `the_title` filter hook. so create your function , something like this: function custom_menu_title($title,$post_id){ return $title . ' ' . get_post_meta($post_id,'meta_key',true); } and you hook it before you call `wp_page_menu` and remove it right after so: add_filter('the_title','custom_menu_title',10,2); wp_page_menu(array(...)); remove_filter('the_title','custom_menu_title',10,2);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Display newest post's custom field content on homepage, daily Ok, so I'm pretty confident on how to display a certain post's custom field content on my home page, or wherever I wanted it. But what I'm trying to do is this: I have my main home page that I want to display content from the newest post everyday. In other words, I have an area where I need to display the newest post's custom field content daily. Automatically. I will be posting a new post every morning. I don't want to have to go in and edit the home template page everyday though. I would like to setup the home page template to automatically pull in the info. So every morning, after publishing my post, this block will show the custom field content in it. Can anyone point me in the right direction? Thanks!
It sounds like what you need is a custom secondary loop, probably using `WP_Query`, that just queries for your single most recent post. Once you have that, you can use `get_post_meta()` to grab the custom meta from that post in a new loop. * * * Edit: Alternately, you can use `get_posts()` to get the first post's ID and use that. Something like this: $my_most_recent_post = get_posts( 'numberposts=1' ); $my_most_recent_post_id = $my_most_recent_post[0]->ID; get_post_meta( $my_most_recent_post_id, 'my_custom_field', true );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field" }
Plugin: Events Manager - Search by start date only EDITED MY QUESTION TO MAKE IT WAY MORE CONCISE Using Wordpress plugin Events Manager, my goal is to alter the search form so it searches for events on single dates. I don't want a date range search which is built in. Most of my events are nightclub events, which carry on to the next day. Therefore, I also want to alter the event search so that if i search for say Saturday August 18th, I don't want it to display events that started on friday but ended on saturday at 3am.
I discovered a setting that solves this problem without having to hack the code: Events manager settings page -> Pages tab -> Event/List Archives You'll find an option "Are current events past events?" set to yes. This will, for example, cause searches for sunday to not display events that started the saturday before. Then just make the search form have a date input but not a date range input.. Seems to work great for me.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "search, events" }
Blocking adsense ad units for a particular country So I have got one hater in India who bombarded on my adsense ad units. Luckily I didn't get banned from Google. I have blocked Indian visitors from my site using iq-blockcountry plugin (wordpress). Now I want to know if there's any procedure so that I can allow the Indian visitors but hide the adsense units from them? I don't want to block all visitors just because of one foolish person.
A quick google search gave me this. This plugin seems to have this feature: < How can I show different ads to people in different countries? If you install the Country Filter plugin (with the IP database) then you can use the following code in the direct ad insertion modes. This will not work in mfunc mode! <?php if (function_exists('isCountryInFilter')) { ?> <?php if(isCountryInFilter(array("uk"))) { ?> UK advert <?php } else { ?> Global advert <?php } } ?> \-- since above is a paying option. what you can do is . use remote_addr to get your visitors ip $ip = $_SERVER['REMOTE_ADDR']; next use a networkservice that can provide you this information, or you can make functions for that yourself using available databases. \--- your easiest solution would be to use `geolocation`, but then your users have to agree with this.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "adsense" }
Generate page title tag from the content of H1 Is there any way of generating the title tag of a page from the content of an H1 tag on my wordpress page? I've got some dynamically generated content pulled in via an external XML feed and and at the moment, as the page isn't physically generated via the wordpress admin system and is just using a template, the page title is just staying the same regardless of the content. However, I was just wondering whether it would be possible in php, to grab the content of an H1 on a page and generate the title tag from that? Any tips / advice would be greatly appreciated :) Thanks
If you can pull the XML feed before the Title gets set then you could easily use information from the XML feed (and thus the H1) in the title. I guess you need to ask yourself these questions: * Can I pull the XML before the title is processed? * When creating the H1 are there any other dependencies that are only available after the Title is created preventing you from doing this before header.php If you can then you just need to add your code and some conditional statements to the Title tag within header.php
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "title, get the title" }
Best way to count visitors? I want to count how many people visit my wordpress-website an want to know the following data: * visitors per day/week/month/year (with history) * which subpage/article attracts the most visitors Is there a plugin that can do that?
There are a number of ways of achieving this but the two ways I would concider would be * **Google analytics** \- < * **Wordpress Sitestats** \- < or install < as it comes with that.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, count" }
Which hook should be used in this case? I'm using the enter_title_here filter to modify the 'Enter title here' text in a custom post type, question is what hook should I use to trigger this function? I have used admin_enqueue_script as a test and it worked, but I think there is a better hook since this is not really a script. function print_scripts() { $screen = get_current_screen(); if ( 'post' === $screen->base && 'myposttype' === $screen->post_type ) { wp_enqueue_style( 'styles', WP_CSS . 'styles.css' ); // filter used here add_filter( 'enter_title_here', function() { _e("Enter name here"); } ); } } add_action( 'admin_enqueue_scripts', 'print_scripts' );
Answer was the one by @RutwickGangurde: You just need to call the filter enter_title_here. No action hook is required for that. Yes, for enqueuing the script, admin_enqueue_scripts will do.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, hooks" }
Modify message displayed on post save After a post is updated there is a message displayed, how can I change the displayed text? I would like to remove the "view post" link and change the 'Post published' text. I'd like to do this for a particular post type. Here is the html WordPress outputs: <div id="message" class="updated below-h2"><p>Post published. <a href=" post</a></p></div>
Solved: add_filter( 'post_updated_messages', 'feed_updated_messages' ); See <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "filters, hooks" }
Full Width Main Post On my site I want to add a section just below Navigation and above-content (from where posts starts to show up on front page) which would show a panel where I can put any BREAKING NEWS (not always, whenever I want) with its excerpt and image. That panel should stretch with max-width. I want to pull that BREAKING NEWS from a specific category say - category_breaking. Is it possible? If yes, then how? Thanks for the help. I want to achieve exactly like this - (
It's certainly possible, and is a common thing to do with WordPress: <?php $q = new WP_Query('category_name=category_breaking'); // query that gets all posts in category "category_breaking" if( $q->have_posts() ) : // if there are posts returned by query... echo "<div id='breaking_news'>"; // start the breaking news section while( $q->have_posts() ) : $q->the_post(); // start looping through query results echo "<div class='bn_post'>"; // single breaking news post start echo "<h2>".get_the_title()."</h2>"; // display breaking news post title if(has_post_thumbnail()) // if post has featured image set... { the_post_thumbnail(); // then display featured image } echo "</div>"; // close single breaking news post endwhile; echo "</div>"; // close breaking news section endif; ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, categories" }
Embed interactive pdf I have interactive pdf documents that I need to put on a wordpress site. Visitors need to be able to fill these in and print them out to sign and post. They do not need to be emailed or saved to the site. I have tries embedding them with all kinds of plugins but all they do is embed a non fillable pdf. What I need is this : < Hope anybody can help. Kind Regards, Marja
* How did you tried to embed them? * Is it post or page? My solution would be to add it into an `iframe` , add code below as html to your page/post. <iframe frameborder="1" height="200" name="frame1" scrolling="yes" src=" width="550"></iframe> you should change the `width` and `height` accordingly ofcourse. Let me know if it worked.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "forms, embed, pdf" }
wp_get_archives() - Get CSS selector for current month I'm looking for how to get a class in the wp_get_archives functions to get the current month (when we are in a month archive) just like when we call wp_list_categories, the current category has a ".current-cat" selector for CSS or when we call wp_list_pages we have a '.current_page_item' selector.
This function was created with the great help of Joshua Abenazer. Thanks! Basically, if is a monthly archive, go and get the current month watched, and add a class on the li. Worked great. function wpse_62509_current_month_selector( $link_html ) { if (is_month()){ $current_month = get_the_date("F Y"); if ( preg_match('/'.$current_month.'/i', $link_html ) ) $link_html = preg_replace('/<li>/i', '<li class="current-month">', $link_html ); } return $link_html; } add_filter( 'get_archives_link', 'wpse_62509_current_month_selector' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "css, wp get archives" }
How to post data to a word press site in case of a mobile app I have a site made with word press. I came across a requirement where a developer tries to log in from an ipad or iphone into word press site. Is there any plugin to achieve this ?. there is a necessity to get back the data in json format and give to developer !!
When you say developer, I immediately assume you mean someone trying to add content to the site? There is a WordPress app that you can add your site to, and add Posts, pages, view stats, etc.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "php, user access, json" }
Running a function only once when a taxonomy term is changed Probably quite a simple problem.. I have a custom post type with taxonomy terms. I wish to run a function from my functions.php whenever the admin ticks a specific term box. My original thought was to use add_action along with a "save_post" action so when the post is saved, it would loop through my terms and if the desired one is selected, it would run the function. This is all good, except each time the admin updates the post it would run the function. The function is sends an email to a user, and I onyl want this email sent out ONCE. Is there any way I can set it so once the function runs it will not run again? I thought about updating a row in the DB and adding a "1" for example when the function runs, and having an if(){} within the fucntion to check if it had been ran before, but this seems like a dodgy way of doing it :/ Thanks!
In your emailfunction, check if the date is difrent from the publish date, if so, don't email. This will cause you to email only once?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, functions, terms" }
How to add and remove a page I'm creating a plugin that will need to add a new WP page upon activation and then I want it to remove that same page upon uninstallation. Do I have to manually store that page id in the DB somewhere or is there a native WP option to remember that automatically? My code so far: register_activation_hook(__FILE__, 'create_page'); register_uninstall_hook(__FILE__, 'remove_page'); function create_page() { global $user_ID; $page['post_type'] = 'page'; $page['post_content'] = 'Page content will go here.'; $page['post_parent'] = 0; $page['post_author'] = $user_ID; $page['post_status'] = 'publish'; $page['post_title'] = 'Page Title'; $pageid = wp_insert_post ($page); if ($pageid == 0) { echo "Something went wrong. Could not successfully add a new page."; } }
Why do you need to create a page? Its possible that before plugin deactivation, the page no longer exists, so your deletion function will need to check for if it exists But yes you will need to store the ID somewhere. Best option is to just update_option('icreatedapage', $pageid); if ($pageid == 0) { echo "Something went wrong. Could not successfully add a new page."; } else { update_option('somename_relatedtoyour_plugin_name', $pageid); } Tho what do you do if you page fails to create? You will need to considering including instructions on how to manually create it, or let the user do it themselves...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development" }
WordPress and Git: How does Git interact with your IDE? Everyone has been telling me I should use Git. What I don't understand is how git interacts with your IDE. Say i'm developing on Dreamweaver, and I switch branches, my IDE isn't going to reflect that so how do I get the two aligned? Plugins? = more complicated than simple FTP sync ... Or am I missing something?
I don't know Dreamweaver at all, but it certainly has the ability to know when an underlying file has changed, yes? Suppose you open an html file in Dreamweaver. Suppose you open it also in vim or TextWrangler; were you to save it in vim or TextWrangler, would it throw an alert to reload the file in Dreamweaver? If so, that's all changing branches will do. Unfortunately, Dreamweaver doesn't have direct git integration the way, say, Eclipse or IntelliJ do.
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "version control, git" }
Remove the Yoast SEO Post Metabox Yoasts SEO plugin adds a metabox to the post edit screen. I'm trying to remove this for users who aren't editors or above. I've tried putting a `remove_meta_box` call in on admin_init, trying to remove the action on $wpseo_metabox but to no avail. How do I remove this metabox without requiring user intervention (the user should never know the metabox existed, so clicking on screen options is not an option )
On `remove_meta_box` is a note: > Because you can't remove a meta box until it's been added, it's important to make sure your call to remove_meta_box() happens in the right sequence. WordPress SEO adds meta boxes on `add_meta_boxes` action with default priority - 10, which run after `admin_init`, so that won't remove them. Instead you need to hook into `add_meta_boxes`, but with lower priority - 11, 12, etc. function mamaduka_remove_metabox() { if ( ! current_user_can( 'edit_others_posts' ) ) remove_meta_box( 'wpseo_meta', 'post', 'normal' ); } add_action( 'add_meta_boxes', 'mamaduka_remove_metabox', 11 );
stackexchange-wordpress
{ "answer_score": 17, "question_score": 8, "tags": "metabox, plugin wp seo yoast" }
Convert the_permalink() function output into string How can I convert functions like the_permalink() into strings like $permalink?
Use `get_permalink()` function which returns a value instead of printing it. **Example -** $permalink = get_permalink($id); //$id if using outside loop
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, functions" }
help getting featured image using get_posts I am using a homepage sorter to arrange the posts on the front page of my site because of that, I am getting the posts in this manner so that I can call each post individually instead of in a foreach loop $args = array( 'numberposts' => -1,'category_name' => 'homepage'); $home_post = get_posts( $args ); $image = get_the_post_thumbnail($post->ID); global $more; $more = 0; Then I can call each post this way <?php if( isset( $home_post[1] ) ) { ?> <p><?php echo $home_post[1]->post_excerpt; ?></p> <?php } ?> My problem is that get_posts has no way to get the post thumbnail outside of using a loop. I can't use a loop because I need my post called in a switch statement. I can't find a way to get the post thumbnail. Do you know of a way?
`get_the_post_thumbnail()` expects the post ID as first parameter. So you need a post object like … `$home_post[1]`. echo get_the_post_thumbnail( $home_post[1]->ID ); … should do what you need.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "images" }
What filter or action hook to use in order to load some code before the template begins printing in BuddyPress? I would like to load some code before the template begins printing in BuddyPress. What filter or action hook should I use? I tried a number of them (such as `bp_head`, `bp_include`, `bp_init`), but none of them seem to work. My code is simply never loaded. The list of filters and action hooks is hundreds of entries long, which is a bit overwhelming to me, since I am fairly new to BuddyPress. So any help would be greatly appreciated. I am trying to tell BuddyPress to use a different template if certain conditions are met. So I have some code in bp-custom.php and I would need the appropriate filter or action hook to get it working. Preferably one that accepts a `$template` variable as an argument. EDIT: I've tried with different action priority numbers (or without) and nothing seems to work. Still need help with this!
Untested, but I'd start with something like this: add_action( 'wp', 'your_function', 3 ); function your_function(){ if ( is_page_template( 'some-template.php' ) ) { if( some condition ) locate_template( array( 'some-other-template.php' ), true ); else return; } else return; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, filters, hooks, buddypress, actions" }
How can I json_encode the output of my function? How can I json_encode the output of this function I use to get all attached images of a post? <?php function get_all_images($postid=0, $size='bigger', $attributes='') { if ($postid<1) $postid = get_the_ID(); if ($images = get_children(array( 'post_parent' => $postid, 'post_type' => 'attachment', 'numberposts' => -1, 'orderby' => 'menu_order', 'post_mime_type' => 'image',))) foreach($images as $image) { $attachment=wp_get_attachment_image_src($image->ID, $size); ?><img src="<?php echo $attachment[0]; ?>" alt="" /><?php } }?> Everything is already setup for admin-ajax.php.
Not sure if the `get_all_images()` function is the one that is added to your wp_ajax_{action} hook. If it is you will want to output a string back to your js. I would define a variable and concatenate the img html to it as you loop through your images. function get_all_images() { //your code $response = ''; foreach($images as $image) { $attachment=wp_get_attachment_image_src($image->ID, $size); $response .= '<img src="'.$attachment[0].'" alt="" />'; } die( json_encode( $response ) ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "functions, ajax, json" }
what is template-name.php A while back I found that there was a reason to name a template like so template-name.php For the life of me, I can't remember what it was for. I thought it was so that WordPress would automatically pick up that template so that you would not have to set the page template when creating the post. I have been looking in the codex for an hour and can't find it. Do you know what the logic is behind this?
I always name them like so: page-name.php; This keeps my page templates nicely together + in some cases this can make your code easier, for example... <?php // Get the file called loop-page.php get_template_part( 'loop', 'page' ); ?> A quick Google revealed also this < Cheers
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates" }
List of Default Translated Phrases With `<?php _e('Save Changes') ?>`, I know the phrase, "Save Changes" can be translated automatically if the user's locale is set to a different language. I'd like to know if there is a list of those already translated WordPress default messages. What else can I use?
The list is available in `$GLOBALS['l10n'][ $text_domain ]`. To get the looong list of translatable WordPress strings just use: print '<pre>' . htmlspecialchars( print_r( $GLOBALS['l10n']['default'], TRUE ) ) . '</pre>'; **Do not use these strings in your theme or plugin.** They are internal, de facto _private_. They can change any time, even in minor updates. Always use your own strings only, even when you think: _this was stable for years!_ Recently the `HTML` tab in the post editor has been renamed to `Text`. I wonder how many plugins will break now … :)
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "translation" }
Wordpress Login Box horizontal at the top. Okay so I learned how to add the wordpress login box to the site. I don't want the box style in sidebar but more of horizontal box in the top of the page under the menu in horizontal way. Are there any pointers for going with this route?
Use `wp_login_form()` and set the `p` elements per CSS inline, so they can sit side by side: #loginform p { display: inline; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login" }
Detect featured image among the attached images I use the following code to extract the attached images from a post with ID: $args = array( 'post_type' => 'attachment', 'post_parent' => $product_id, 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => -1 ); $attachments = get_posts($args); The problem is that the above code return all the attached files. Is there a way to remove from the results the featured image ? I don't mind if I will do it through the $args query, by some if statement or by filtering the $attachments array. Kind regards Merianos Nikos
Simply add an `post__not_in` argument and use the `get_post_thumbnail_id()` function. $args = array( 'post_type' => 'attachment', 'post_parent' => $product_id, 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => -1, 'post__not_in' => array(get_post_thumbnail_id($product_id)) ); $attachments = get_posts($args);
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "wp query, wpdb" }
Divs appearing everywhere in post content Whenever somebody writes a post on our site, the Paly Voice ( there are automatically a lot of `<div>` elements created. This is bad for layout, since we have a style that applies to divs that we don't want to apply to story styles. Is there a way to remove the automatic div insertion? If not, can I add a function hook to parse the post and remove them before saving to the DB? Edit: Example here: <
You first should find out where the divs are coming from, since that's not normal behavior. Could be from a plugin or - as Damien said - copy-pasting a text from Word. To remove the divs you can do a simple str_replace(array('<div>', '</div>'), '', $content) either before storing the text in the database (by hooking on `save_post`), or before displaying it on the site (by adding a filter on `the_content`). EDIT: I was wrong, you don't hook on `save_post`, but instead you filter on `wp_insert_post_data`. This function below should work: function remove_divs($data) { $filteredContent = str_replace(array('<div>', '</div>'), '', $data['post_content']); $data['post_content'] = $filteredContent; return $data; } add_filter('wp_insert_post_data', 'remove_divs', 99); Put this in your functions.php
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, hooks, html, actions" }
How to include a plugin's php file to another plugin functions file I need to customize the output of the shortcode of plugin A by using a function of plugin B. So I alter the shortcode function of plugin A by inserting a condition to check the value of the function of plugin B but I need to include the php file that supports this function. I tried all require_once, require and include but I get the following errors: When using `require_once('../../pluginname/pluginfunctions.php');` Error Warning: require_once(): open_basedir restriction in effect. File(../../magicmembers/core/libs/functions/mgm_misc_functions.php) is not within the allowed path(s) When using `include(WP_PLUGIN_URL . '/pluginname/pluginfunctions.php');` Error Warning: include(): URL file-access is disabled in the server configuration What is the correct way?
The first error message means that there is restrictions in place on where you can include files from, set by the server. You could try with require_once ABSPATH . '/wp-content/plugins/pluginname/pluginfunctions.php'; but I'm not sure if it would work. With the second include you're trying to include an URL which is disabled by the server for security reasons. However, why do you need to include the function of plugin B? If plugin B is present that means it's probably activated, which in turn means you can use the function directly from plugin A without needing to include the file specifically.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 9, "tags": "plugins, functions, include" }
Problem with caching, W3TC Am using W3TC from a long time but from past few weeks am stuck, as I can't see my edits working. It was all fine in past but from a week my edits in style.css reflects back in like an hour after.
The best way I can think of is to add a unique string to the end of the stylesheet include to get everything to update. For example, if you are including it in the header.php file: <link rel="stylesheet" href="<?php echo get_stylesheet_uri(); ?><?php echo '?v='. time(); ?>" /> Of course that will keep it from being cached... ever. So you might want to turn it off and on. You could add a variable to activate it or you could tie it to wp_debug: <link rel="stylesheet" href="<?php echo get_stylesheet_uri(); ?><?php if ( defined('WP_DEBUG') && ! WP_DEBUG ) echo '?v='. time(); ?>" /> Or just comment it out when you are done: <link rel="stylesheet" href="<?php echo get_stylesheet_uri(); ?><?php #echo '?v='. time(); ?>" /> You can use all of those if you are enqueueing the styles as well.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "cache" }
Pagination for custom post types Hi I have a custom post type and its posts are called via a shortcode on any other post or page. I'd like to paginate this post type, say display 10 items. So the page in the URL remains the same, but the content inside (via shortcode) changes when I go to the 2nd page from the pagination buttons. How do I do this?
Try to do a little research. This is documented all over the googlesphere. < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pagination" }
background images WP Supersized on homepage I'm using the WP Supersized plugin to load background images on posts and works fine. The problem I have at this point is I want to show the latest post in cat 17, with custom field key FeaturedOnHomepage, with value yes on my homepage and display the background images from that post. Below the query I use: <?php query_posts('cat=17&posts_per_page=1&meta_key=FeaturedOnHomepage&meta_value=yes'); ?> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> <?php endwhile; ?> <?php else : ?> <?php endif; ?> Somehow WP Supersized is getting confused and is showing the default image folder (like all images in the Media Library. Do I need to include code to make this work?
Never mind. Switched to < Much more control and working like a charm.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, query posts" }
Mysqldump add drop table? I notice in the Codex that the --add-drop-table option is displayed for backing up a database. Before I screw anything up, does this just mean that when the backup is eventually imported, the tables will overwrite if they exist in the destination db? I don't want to drop the tables when I back them up! user@linux:~/files/blog> mysqldump --add-drop-table -h mysqlhostserver -u mysqlusername -p databasename (tablename tablename tablename) | bzip2 -c > blog.bak.sql.bz2 Enter password: (enter your mysql password) user@linux~/files/blog> <
It only affects the output of your MySQL dump in the file that is created. It isn't necessary. It is just there so that if you import the created dump file into a database that already has a table with the same name, it will drop that table and then add the new table in its place. Otherwise you will get an error, and the dump file won't be imported. It adds this line before the create table statement in the dump file: DROP TABLE IF EXISTS `tablename`; If you plan to import the dump file into a fresh database, it won't matter.
stackexchange-wordpress
{ "answer_score": 11, "question_score": 11, "tags": "mysql, backup" }
Search.php gets metadata from first post I've got this in header.php in `<head>` section: $page_color = get_post_meta($post->ID, 'page_color', true); It works fine because it gets correct `page_color` for posts and pages but when I perform some search and search.php is run, it occasionally gets `page_color` of first post it finds. This is the content of search.php: <?php if( have_posts() ) : while (have_posts()) : the_post(); ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> <?php the_excerpt(); ?> <?php endwhile; ?> <?php else : ?> Nothing found. <?php endif; ?> Any ideas why is that?
I don't think it's just occasionally, that will _always_ get you the post meta of the first post on a search results page, a taxonomy page, an archive page - any page where there are multiple posts, because the `$post` global will always be populated with the first post of any main query result. **EDIT-** if ( is_singular() ) : // we are viewing a single post or page $page_color = get_post_meta($post->ID, 'page_color', true); else : // not a single post or page, use a default color $page_color = 'blue'; endif;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, theme development, wp query, loop, search" }
URL rewrite( I think? ) I have a URL: www.example.com/my_cool_pancakes. When a User goes to this URL, I would like the URL to instead be www.example.com/pancakes. How do I do this? Is this URL rewriting? I have studied URL rewriting, but I am still not sure about how it works, or even if it is the method I should use to do this. If it is, could you show me how? Thank you :) PS: www.example.com/my_cool_pancakes is an archive page template for a custom post type if that makes any difference.
Could using the register_post_type parameters fit your needs? There's an option "slug" that will do so if has_archive is set to true...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "url rewriting" }
conditional tags- how to use with shortcodes I have a salon website with a gallery page wherein the user must first select a stylist prior to viewing their individual gallery. I planned on using NextGen to house the images in stylist specific galleries, and using the NextGen shortcodes(ex: `[nggallery id=1]`) to determine which gallery gets shown on the specific page. After doing a bit of research, I think WP's conditional tags (I'm thinking `is_page( # )`) might be the best route to take for this, I'm just not sure how to integrate the conditional tags to specify/define the page and the NextGen shortcodes. Any tips, help, advice, etc. is greatly appreciated.
I am not sure to understand your question, but you have to read more wordpress/nextgen documentation. What you need to do exactly? Can you be more specific? I think, that if you create a set of pages (for each stylist) and use the respective shortcode of the gallery in the content, this will work fine. ex: in the page REBECCA HAEHNLE (page_id=29) use `[nggallery id=ref_stylist_galery]` On the mother page (gallery), use the album shortcode (create an album with all the stylists galleries in order you want) `[album id=ref_album_id template=extend]` I think it will do the trick :) In other words, you can do something like this in your **page.php** template: if( is_page(ID_OF_SPECIFIC_PAGE) ) { // make your stuff here echo do_shortcode('[nggallery id='.$my_id.']'); } else { // output standard content here }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "pages, shortcode, gallery, conditional tags" }
How to define a custom font family for a wordpress blog that will not affect the entire site While my related question on Stack Overflow _should_ explain the basic CSS for this once it gets answered, how would I define a custom font family for a wordpress blog that will _only_ apply to a <span> and will not affect the site-wide font families being used by the theme on my wordpress site? > Related: Creating Useable Custom Font Family
You can use this function: < Use this in your header.php <body <?php body_class(); ?>> This gives each page a different class and so you can use CSS to set the font-family for a specific page like so: body.blog span.yourClassName{ font-family:; } Then of course the is also the jQuery solution using the .children() function
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "formatting" }
Problems updating wordpress When I try to update wordpress from 3.2.1 to the latest one it stalls and does nothing. It used to ask for my ftp details, which I looked up online and added this to the wp-config: /** Setup FTP Details **/ define("FTP_HOST", "localhost"); define("FTP_USER", "your-ftp-username"); define("FTP_PASS", "your-ftp-password"); This seems to have stopped it asking for ftp details, but it gets to a page and just does nothing, below is a screen shot of what I see. Any ideas of whats going wrong? !enter image description here
Try adding all of the following: define('FS_METHOD', 'ftpext'); define('FTP_BASE', '/path/to/wordpress/'); define('FTP_CONTENT_DIR', '/path/to/wordpress/wp-content/'); define('FTP_PLUGIN_DIR ', '/path/to/wordpress/wp-content/plugins/'); #define('FTP_PUBKEY', '/home/username/.ssh/id_rsa.pub'); #define('FTP_PRIKEY', '/home/username/.ssh/id_rsa'); define('FTP_USER', 'username'); define('FTP_PASS', 'password'); define('FTP_HOST', 'ftp.example.org'); define('FTP_SSL', false); This is sourced from the official wp-config document here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "upgrade, updates" }
How do I go about fixing this apparently messed up upgrade? I'm a WordPress novice trying to help a friend (who is even more of a WordPress novice) with his WordPress blog hosted on GoDaddy. It was working fine until he apparently (he doesn't fully remember) was prompted to upgrade the software. Now the blog still works for end-users (you can see it here) but whenever you log into the WordPress admin, you get a Page Not Found / "This is somewhat embarrassing, isn’t it?" page. The URL that the browser has been redirected to is: ` It seems like the upgrade attempt was messed up somehow. Given I don't know what precisely caused this, what steps should I take to start investigating the problem and ideally rolling back the upgrade (or completing it) so that the blog is usable again?
Thanks for the other answers. Turns out GoDaddy had run an upgrade patch for WordPress which never finished. I reran the patch via GoDaddy and that fixed it!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "404 error, upgrade" }
Custom posts per page does not work with pagination I have one page in my template where I would like to set a custom posts_per_page. Here is the code I have used: <?php global $query_string; query_posts($query_string . '&posts_per_page=4'); if ( have_posts() ) : while ( have_posts() ) : the_post(); ... Now this code limits only 4 items per page and shows pageinate_links below as I have written. However clicking on any other page will lead to a 404. If I take out the global and query_posts line then it works fine. This is the paginate_links function I am using: echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages, 'prev_text' => 'Previous', 'next_text' => 'Next', ) );
Use a `pre_get_posts` action in your `functions.php` with conditional tags, and remove the call to `query_posts`: function wpa62751_pre_get_posts( $query ) { if ( is_category( 'my-category' ) && is_main_query() ) $query->set( 'posts_per_page', 4 ); } add_action( 'pre_get_posts', 'wpa62751_pre_get_posts' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "query posts, pagination, paged" }
How to get IDs for objects in menu branch? Is it possible to print content of all menu items, when displaying menu (or branch of menu as in question about displaying menu branches) ? !enter image description here Once I click on `About Us` I wish for new page to display content of all it's children links. So basically I am looking for a way to get IDs of those posts/pages and use them inside my WP Query.
I am lazy to write supporting logic from scratch so I am reusing functions from linked answer on branches: /** * Retrieve IDs of posts in branch of menu. * * @param mixed $menu * @param string $branch_title * * @link * * @return array */ function get_post_ids_from_menu_branch( $menu, $branch_title ) { $menu_object = wp_get_nav_menu_object( $menu ); $menu_items = wp_get_nav_menu_items( $menu_object->term_id ); $items = submenu_limit( $menu_items, (object) array( 'submenu' => $branch_title ) ); $items = wp_list_filter( $items, array( 'object' => 'post' ) ); $ids = wp_list_pluck( $items, 'object_id' ); return $ids; } // example var_dump( get_post_ids_from_menu_branch( 'Test menu', 'Level 1' ) );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 6, "tags": "menus, templates, page template" }
Is it possible to control content on different pages by checkboxing wich content is shown where on a wordpress theme page? i have created a sidebar in my wordpress site. i want this sidebar to be displayed on each of my pages and subpages in their respective admin editors. i want the sidebar to contain a list of specific posts with checkboxes to select them independantly or together. each checked post must then be displayed on my site where i call the sidebar. is this possible? can anybody direct me towards a plugin that can accomplish this?
You can use the WordPress Settings API to do what you're looking for. You can follow this - WordPress Settings API Tutorial _( www.ottopress.com )_ to setup an options page, and depending upon the options saved in database you can show different content. **Example -** <?php // get the stored value in variable - foo $foo = get_option('option_name'); if ( $foo == 1 ) { echo 'check box in CHECKED'; } else { echo 'check box in NOT CHECKED'; } ### Update - Yup there's Options Framework plugin plugin which can be used for this purpose. > The Options Framework Plugin makes it easy to include an options panel in any WordPress theme. It was built so developers can concentrate on making the actual theme rather than spending time creating an options panel from scratch. It's free to use in both commercial and personal projects, just like WordPress itself. \- A Quote from plugin's description
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "plugins, widgets, sidebar" }
Script for initializing JQuery Masonry for Wordpress What is the different between this ( and ( for JQuery Masonry. Why does the first one work and the second one doesn't. In both cases I used wp_enqueue_script to add the script. Thanks!
This executes, when the DOM has been constructed, before all content has been loaded $(document).ready(function(){ ... }); $(function(){...}); // short form This executes, when all content has been loaded $(window).load(function(){ ... }); This executes immediately, when it is first encountered by the browser (function(){ ... })(); The latter is known as a self-executing anonymous function, which is very handy, but not here, because no content or not the right content may have been loaded when it self-executes.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "jquery" }
How to allow empty title for attachments? * When adding an image attachment to a post, the Title field is always filled automatically with the file name. * For some images I change this into something more meaningful, for other images I want this field to be empty (in my theme I'm displaying this title field as a caption below each image, but not all images should have this caption). * However, if I clear the Title field, it shows again the file name upon save - with the message " **Empty Title filled from filename.** " * Any ideas how to change this behaviour, or suggestions for a workaround? I could use the Alt field or Caption field, but I prefer using the Title field - so my client can already fill in the titles by changing the filenames before upload.
Without a post title, Attachments become significantly harder to use as they no longer have a title that can be clicked on. If you're processing attachments and generating html manually I recommend using another piece of attachment meta, or just filling in appropriate titles, after all an image is a picture of something, let that something be its name, there's nothing stopping duplicates either. If you really must remove the title, go to the html tab and manually remove it from the tag. Else put in a placeholder character such as '-'. Ofnote, attachments are posts too, and that means they have post meta. **You could add a checkbox to the edit attachment page** , allowing you to toggle on and off wether the attachments title is displayed or not.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "attachments" }
How to hide a custom post type I've got a wordpress website and i need to hide for the moment some custom post type. I want to hide it because we will need it later. How do I do it?
There is a parameter named "public" where you can set if you want the custom post type to be private or public add_action( 'init', 'create_post_type' ); function create_post_type() { register_post_type( 'acme_product', array( 'labels' => array( 'name' => __( 'Products' ), 'singular_name' => __( 'Product' ) ), 'public' => false, 'has_archive' => true, ) ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
assign the returned value of wordpress function to a variable? Why can't I store wp_list_categories in a variable? $wplist = wp_list_categories( array ( 'taxonomy' => 'ntp_package_type', 'pad_counts'=> 0, 'title_li' => '', ) ); var_dump($wplist); //null
You need to set the echo parameter to false. The function defaults to echoing the output rather than returning it. $wplist = wp_list_categories( array( 'taxonomy' => 'ntp_package_type', 'pad_counts' => 0, 'title_li' => '', 'echo' => false ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "variables, categories" }
How to automatically create a custom field when a post is published? I'm trying to add custom fields on post publish with this code which I added to my functions.php : add_action('publish_page', 'add_custom_field_automatically'); add_action('publish_post'. 'add_custom_field_automatically'); function add_custom_field_automatically($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { add_post_meta($post_ID, 'FIELD_NAME', 'CUSTOM VALUE', true); } } This code should work but it doesn't ? I updated field and custom value but custom fields are never created.Why ?
add_action('publish_post'. 'add_custom_field_automatically'); You have a period in the second add_action. This should be a comma :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "custom field, functions, hooks" }
Facebook Like Button with NextGen Gallery i'm following this tutorial: < for implement Facebook Like Button on this plugin. It's working very well, but if you like the picture, this "like" does not appear in your timeline on facebook. On the photo you see the "countdown" of likes, but it not appearing on timeline... Any script that is missing so there is your "like"?
why not use this plugin ? NextGEN Facebook Adds Facebook HTML meta tags to webpage headers, including featured images. Also includes optional Like and Send Facebook buttons.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, facebook" }
Remove url parameter using wordpress how can I remove a parameter from a URL in wordpress? for example if I have the following URL: How can I remove paged from it?
You should use pretty permalink. Please read this docs from WordPress Codex for full information.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "url rewriting, urls" }
Function to show only first instance of shortcode I need to add a function to my theme to remove additional instances of a shortcode in a post. First off I wonder if i'm approaching this wrong, but I have a theme that is drastically reformats the way a post is laid out. In the post we look for media and shortcode and then display them at the top of the page, basically stripping it from the content and placing it before the title. The conditional statement checks for the existence of a featured image or a gallery shortcode, then prints it. The problem i'm running into is that the gallery is printed again in the the_content(). What i'd like to do is create a function to strip the shortcode after it's been printed the first time. I'm aware of this hook remove_shortcode() but this will remove all instances of that shortcode where I only want to remove it after the first has been printed.
Add a static variable to the shortcode handler to check if the shortcode has been called already. ## Sample code add_shortcode( 'wpse62826', 'wpse_62826_shortcode' ); function wpse_62826_shortcode() { static $done = FALSE; // Nothing to do. if ( $done ) { return; } if ( is_singular() ) { $done = TRUE; } return '<b>I run once on singular views!</b>'; } ## Result ![enter image description here](
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "functions, loop, shortcode, the content" }
Is there a way to insert multiple images into a post at the same time without using a gallery? I'm trying to find a way to add multiple images to a blog post in wordpress at the same time. I want to be able to write text above and blow the images, just like a normal blog post. It takes a lot of time to add each image one at a time (especially if there are like 50 or so images in a post.) I can do a gallery, but that doesn't allow you to write content above and below. Any ideas on how I can do something like this? Thanks.
I found this plug in which lets you do just this very things. It works great! <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, theme development, images" }
wp_nav_menu show 1 item only I was reading Wordpress documentation and also trying to find some clear example of how to do this but I couldn't, sorry if this is posted elsewhere but I did my best trying to find an answer before posting. My question is simple, if I use the wp_nav_menu function of wp, what should I do in the array or any other place to show one specific element and it's childs. So for example, I have a menu Home, About, Services. My question would be how to show only Services for example with it's childs. Is that even possible? Thanks in advance.
After searching some more I found this great answer, they key was to use a custom walker. Display a portion/ branch of the menu tree using wp_nav_menu() Best.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "menus, array" }
How to remove the HOME menu item I am using wordpress 3.4.1. I am mainly creating a static site and for that have created and arrnaged the pages, and wordpress has nicely created the pages in proper nav-menu format for me, which is good. But, it has also added a link to 'Home' in the nav-menu. How can i remove that? NOTE: I prefer any other answer than using the menu section and creating a new menu and assigning it as primary menu.
Here's a good solution posted over at .org < > You can remove the "Home" link using a filter. Add this to your Theme's functions.php file: > > > function mytheme_nav_menu_args( $args ) { > $args['show_home'] = false; > return $args; > } > add_filter( 'wp_nav_menu_args', 'mytheme_nav_menu_args' ); > And if you want to remove the "Home" link from the default fallback menu, add another filter: > > > add_filter( 'wp_page_menu_args', 'mytheme_nav_menu_args' ); >
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "menus, wp list pages" }
How to use custom post type APIs, but use a different db table We currently have a plugin that creates a new WP table, but it recreates the wheel when it comes to managing/updating data. It would be a good candidate for custom post types, but we don't want to pollute the `wp_posts` table. **Use case:** We're creating a specific job board for a company that lists 100s of jobs, and we want to keep the tables clean for other php scripts outside of WP that will also be accessing the same data. Input and management would be handled by the standard WordPress APIs. **Question:** I want to use WP's custom post type functionality, but use a different db table. Thoughts? Directions? Is it possible to simply tell WordPress to switch tables for a certain query? **Related:** Difficult to read and understand, and not entirely the same: Use Custom Database with Custom Post Type
I don't think you can do this. Maybe you could use a whole new database, but it seems unlikely you could add a new table for managing a custom post type. For one thing, a custom post type is stored in the wp_posts table, but some of the data for it gets stored in the wp_postmeta table (especially any post meta fields). And if you have a taxonomy with it, that uses 3 different tables. And if your plugin needs to store any options those would be in another table. I wouldn't worry about polluting the wp tables, it is how they are made to work. Part of its power is the extendability that is built in and easy to use. You could maybe provide a way to remove your post type and all of its posts if you wanted to be able to completely remove it.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "custom post types, wp query, database, wp list table" }
Advice for a Newbie Wordpress Web Designer/ Themes? I am digging into a freelance career and I would like to know what the best advice is out there when it comes to buying themes for clients? What is the best practice? Themeforest? Bundles? What should be my criteria when choosing themes to develop and offer to clients?
Firstly, if you have to re-sell themes then you need to be sure that the licence permits it and that you are being open with the client, no buying a theme for $20, claiming it is your own and charging the client $1000. You should learn how themes work and look towards developing your own to become a web designer, simply re-selling themes makes you a middle man, not a web designer. An honest approach to this is by selling your services as technical assistance, you have your client pick a theme or you choose one based on their requirements and do the installation and set-up for them, alternatively learn how WordPress themes work and offer your services as a web designer to re-brand and modify the purchased template. As for template sites, I like Theme Forest however there are loads of them out there however I cannot stress enough, make sure you are not breaking licence or market place usage terms or you could find yourself in trouble.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "themes" }
Adding a querystring to an image URL when clicking 'insert into post'? I have written a plugin which does some fancy stuff with GD lib when you upload an image. Everything is working fine, however I need to get the image title and add it to the image URL (and file name of the image) when the user clicks 'insert into post', but can't find any references which could help me.
You need to use the filter `image_send_to_editor`. add_filter('image_send_to_editor', 'wpse_62869_img_wrapper', 20, 8); function wpse_62869_img_wrapper( $html, $id, $caption, $title, $align, $url, $size, $alt ) { return $html; } These are the values of a test insert and you can use them to build your own `$html` response. html | <a href=" src=" alt="Alt text for the image" title="escritorio" width="224" height="300" class="aligncenter size-medium wp-image-9" /></a> id | 9 caption | The image caption title | escritorio align | center url | size | medium alt | Alt text for the image
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, images, uploads, media library" }
Delete custom fields when deleting posts When I delete a bunch of posts their custom fields remain in the database, is there a way to remove them as well on deletion?
The best way to do this is to use the wp_delete_post function as follows: wp_delete_post($post_id, true); //false (default) sends it to the trash This function accounts for comments, term_relationships, posts.post_parent, and postmeta.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom field" }
Sorting posts by custom field value I am trying to sort posts by their custom field value, which is a date in this format: 9 August 2012, 7:18 am 'orderby' => 'meta_value', 'meta_key' => 'wprss_item_date', 'order' => 'DESC' Do I need to do some conversion before that can work?
Your date should be stored in descending units, like `yyyy-mm-dd hh:mm:ss` for MySQL to be able to sort on the field. See the MySQL docs for Date, Datetime, and Timestamp data types.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "sort" }
WP_Query not looking at child category Hi all I have a loop that shows a post on a single page and puts the first category name in the variable $cat: $cat = $category[0]->cat_name;?> Now after the post I have a link to show related posts based on this category: $catPosts1 = new WP_Query(array('category_name'=> $cat, 'orderby' => 'rand', 'posts_per_page' => 1)); while ($catPosts1->have_posts()) : $catPosts1->the_post(); The problem I'm having if a Child Category is selected for the first post I.e. Under the category Phones the child category Accessories is chosen nothing is appearing in the related link area. Is there a way of making Wordpress use this child category? Thanks
You'll have to get the child or parent categories yourself and pass all the IDs as an array via the `category__in` argument of WP_Query. You can use `get_ancestors` to get the top parent category, and get all child categories of that parent via the `child_of` argument of `get_categories`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "categories, wp query, loop" }
Can I have two submit buttons in one form? I want to provide 2 buttons in one form. User click either button can submit the form but do different jobs-- one button is to import checked files, another button is to create fiels. Will this confuse Wordpress?
If you're placing a button in a meta box, it is included within the FORM tags for a post. A simple answer is no, you shouldn't place a submit button in the post form. However, nstead of using a normal `input[type=submit]`, use the following: <button type='button' name='button-name' id='button-id'>Button Text</button>' A click won't process as a submit action, it will just click. You obviously will need to bind the click event to however you're importing your file list. If you're not using AJAX, you should. Check out this article on how to use AJAX in WordPress. Having a submit button within the form will post to post.php and certainly will have unwanted effects, namely losing any changed data within the post form.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "forms" }