INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Two domain site: Link base URLs point to wrong domain I have been running domain.co.za, but recently purchased domain.com. Both domains now point to the same Wordpress site. On domain.com pages all the links point to domain.co.za and on domain.co.za all the links point to domain.com, so it flip-flops between the two domains. I am wanting both domain.co.za and domain.com links to point to domain.com. I have set the site address to domain.com, but I have had to leave the WordPress address at domain.co.za otherwise I can't log in. Any help to get all links to point to domain.com and stop the flip=flopping would be appreciated. www.puresweetjoy.co.za and www.puresweetjoy.com
The problem turned out to be that my hosting company had copied domain.co.za to domain.com rather than pointing both domains to the same installation. I was able to update the site URL of domain.co.za to domain.com so all of its links went to domain.com, but I couldn't log in to domain.com so all of its links pointed to domain.co.za, causing the flip flopping. It was my (bad) assumption that I only had one site running.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, links, domain, site url" }
How to get current site id? (WPMU) I am using WordPress with MU activated. I found a function here that supposed to return an object with the current side ID. But it's returning 1 for all websites. <?php get_current_site(); ?>
You're right, `get_current_site()->blog_id` will return 1, as it refers to the network. To get the current site (blog) ID you can go like this: <?php echo get_current_blog_id(); ?> Moreover you can get the current site (blog) details like this: <?php var_dump(get_blog_details()->blog_id); ?>
stackexchange-wordpress
{ "answer_score": 9, "question_score": 9, "tags": "multisite, blog id" }
Display assigned terms with link I want to display product assigned terms, wrapped in link/anchor MarkUp, in my sidebar on a page as a widget. I am not getting the correct tag URL. Code returns visited product URL instead of listed tags URL. Here is the problematic part of the code. What is the correct use of `get_the_terms()`? $custom_terms = get_the_terms( 0, 'product_tag' ); if ( $custom_terms ) { foreach ( $custom_terms as $custom_term ) { echo '<a href="' . esc_url( $term_link ) . '" style="font-size: 8pt;">' . $custom_term->name . '</a>'; } } I guess that something i wrong with `esc_url( $term_link )`, but what?
Keep in mind that the return value of `get_the_terms()` can be of the type of array|WP_Error Your snippet should check if you get the correct type returned $terms = get_the_terms( 0, 'product_tag' ); if ( ! is_wp_error( $terms ) AND is_array( $terms ) AND ! empty( $terms ) ) { foreach( $terms as $term ) printf( '<a href="%s" style="font-size: 8pt; margin-right:5px;">%s</a>', esc_url( get_term_link( $term ) ), $term ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "widgets, tags, terms" }
Admin menu post type Is it possible to get a container post type menu item with all custom post types inside of it?! 1.All post types 1.1 post type 1 1.2 post type 2 1.3 post type 3 1.4 ect....
Yes you can do that. Use function add_menu_page < to add parent "All post types", then use add_submenu_page < to add pages to parent page: add_action( 'admin_menu', 'my_custom_menu_page' ); function my_custom_menu_page() { $slug = 'all-post'; add_menu_page( 'All post types', 'All post types', 'edit_posts', $slug, '__return_true' ); foreach( array( 'post', 'page', 'foo', 'bar' ) as $post_type ) { $title = sprintf( 'Post type: %s', $post_type ); $url = sprintf('/edit.php?post_type=%s', $post_type); add_submenu_page( $slug, $title, $title, 'edit_posts', $url ); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, menus, admin, sub menu" }
Custom Post Type with static page for archive I have created a custom post type `'books'`, but I don't want to use _archive-books.php_ to list the books. I need to use a static page to list my books because I would like to add content using the content editor. I would like this structure: _www.example.com/books_ \----> It is a static page _www.example.com/books/book-title_ \---> it is single post type The problem is that I get a 404 when I try to go into my single post. Can you help me?
Set `has_archive` to `false`. In order to keep the URL structure you want ( _/books/book-name_ ), you'll need to add a rewrite rule: 'rewrite' => array('slug' => 'books'),
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "custom post types, archives" }
Remove a Plugin function through theme's function.php? I am using a Plugin called PixGridder for backend setup, but i dont want the front-end css to apply.. I found that in the plugins functions.php has these lines: public function front_styles() { $theme_style = get_stylesheet_directory().'/gridder.css'; if (file_exists($theme_style)) { wp_enqueue_style( $this->plugin_slug, get_stylesheet_directory_uri().'/gridder.css', array(), $this->version ); } else { wp_enqueue_style( $this->plugin_slug, PIXGRIDDER_URL.'css/front-gridder.css', array(), $this->version ); } } add_action( 'wp_enqueue_scripts', array( &$this, 'front_styles' ) ); My question is, how do i unregister this function? or at least prevent the plugin from looking for the front styles though my Theme functions? - and is it even possible to unregister a function through a theme? Thanks.
Same way you would remove it from anywhere else, be it a plugin or theme or whatever. add_action('plugins_loaded','remove_whatever'); function remove_whatever() { if (class_exists('PixGridder')) { remove_action( 'wp_enqueue_scripts', array( PixGridder::get_instance(), 'front_styles' ) ); } } Might want to use a better function name than "remove_whatever" though. :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions" }
Multisite main theme changes do not show up in child sites I have googled and not found an answer so maybe this is too basic. I have a main site for a school blog, and will create a child site for each classroom. I want each site to use the same basic template which is network-enabled. When I add a header to the theme (as a super-admin), I expected the change to show up in the child sites since they use the same theme. Using the above task as an example, do I really need to go to each child site and add the header separately? Do I instead need to create a child theme in the main site? In general, do any changes in the main theme show up automatically in the child sites?
In a multisite Installation each site is a single blog. It has its own contents and settings. If your change something in the backend of the main blog it does not have an effect on the other blog in the installation. Only if you change something in the code of the theme, it will effect all blogs, which are using the theme, because all blog shares the source files.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite" }
How to exclude one post format from search result? I need to exclude one post format from Wordpress search results. Any suggestions on how to solve this issue?
You could probably do it my modifying the loop through the `pre_get_posts` hook. function wpse163459_search_exclude_post_format( $query ) { if( $query->is_main_query() && $query->is_search() ) { $tax_query = array( array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => array( 'post-format-quote' ), 'operator' => 'NOT IN', ) ); $query->set( 'tax_query', $tax_query ); } } add_action( 'pre_get_posts', 'wpse163459_search_exclude_post_format' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "search, exclude" }
4.0 remove_filter for Wordpress core function not working for me I was trying to overwrite how captions are embedded into a page when editing in the admin. I simply did this: remove_filter( 'image_send_to_editor', 'image_add_caption', 20); add_filter( 'image_send_to_editor', 'update_image_add_caption', 10, 8 ); But it's just not working. I have tried different variations of priorities, and not using them at all, but it doesn't work. Why wouldn't this work? **UPDATE** Here's what I am trying right now, but `$result` always returns false, so the filter isn't removed. function childtheme_remove_filters(){ $result = remove_filter( 'image_send_to_editor', 'image_add_caption', 20); add_filter( 'image_send_to_editor', 'update_image_add_caption', 20, 8 ); } add_action( 'init', 'childtheme_remove_filters' );
From the comments the `remove_filter` is called too early before the core `add_filter` is called. Best way to avoid this is to always remove nd add your filter at the init action add_action('init','wpse163434_init'); function wpse163434_init() { remove_filter..... add_filter..... } This way you are assure that the core had finished initializing and all the core actions and filters are already set. **Update:** all of the above is nice and true, but there is no software without bugs and apparently some filters are added in places where it is really hard to remove them without feeling it is too much off a hack, and `image_send_to_editor` is one of them. Luckily that filter applies the `image_add_caption_shortcode` filter and passes the original html to it so instead of removing `image_send_to_editor` you might get the same impact by using the `image_add_caption_shortcode` filter.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "filters" }
Where does the locale come from? I have currently the problem that I don't understand where the locale that is set in the header of the rendered blog comes from. The header for each post (and all other pages) looks like: <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8" /> ... I tried to find the way to influence the second line `<html lang="en-US">` but could not find it. I tried the following: * Searched in the settings of WordPress site, if the admin can change the default locale, but could not find it. * Used different browsers, and changed in all browsers the language to German. My code to read the locale is: $loc = get_locale(); The documentation for that function reads: Return Values (string) The locale of the blog or from the 'locale' hook. So where can I set the locate in the administration of my Wordpress site, or is there an option to use the locale of the browser?
Locale comes from WPLANG constant defined in wp-config.php. In the last version of Wordpress (4.0, maybe 3.9) something is changing. You can install more languages setting WPLANG to different locale. Then you can select the language in the backend from Settings > General > Site language and set locale in the header. It seems that starting from Wordpress v4.1 will be possible also install new languages from backend.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "localization" }
Where is the best place to catch useragent? I want to add this code: if(preg_match('/(?i)msie [1-8]/',$_SERVER['HTTP_USER_AGENT'])) { // if IE<=8 include ( TEMPLATEPATH . '/noie.php' ); exit; } else { // if IE>8 } from here So I let users know that my website (wordpress theme) is not supporting IE 8 and below. Where is the best place to put this code? Is it in function.php?
You can use the filter `template_include`. `wp-includes/template-loader.php` is where template is included.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, browser compatibility" }
Can't see content on a Mac My account is an administrator. I use a Windows PC. When an editor edits a page I created the content is blank. She is on a Mac using Safari and Opera. She is in Visual mode. If she clicks on Text mode there is nothing there either. It says 0 words underneath. I changed the page so that her account was the author, but the problem remained.
Buried towards the bottom of the page edit page was a PHP memory limit reached error. Increasing the memory limit removed the error, and the content was visible for the editor account.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mac" }
Add custom fields to existing posts (admin pages) I'm able to add a custom field for new posts (in the admin pages), using the action hook `wp_insert_post`. But I would like to add the custom field for old posts, when I am editing the post (in the admin pages), there is any action hook to do that ? Sample code that I'm using: /** * Default custom field for Municipi * @param [type] $post_ID [description] */ function set_default_custom_field_municipi($post_ID){ $municipi = get_post_meta($post_ID,'municipi',true); $default_meta = ''; // value add_post_meta($post_ID,'municipi',$default_meta,true); return $post_ID; } /** add custom fields by default */ add_action('wp_insert_post','set_default_custom_field_municipi'); Thanks in advance,
As Andreas Krischer suggested, I fixed using an script to update all the old values and then only using the `wp_insert_post` to create the custom field for the new posts. The script that I used: INSERT INTO wp_postmeta( post_id, meta_key, meta_value ) SELECT wp_posts.ID, 'municipi', '' FROM wp_posts WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' Here I'm updating all the posts that are with the status publish and are type post, and I'm creating a custom field called `municipi` with initial value empty.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field" }
Product Images Low Quality After Updating From WP 3.5 to 4 I recently updated my WP website from WP 3.5 to recent version 4 and now I am getting a lower quality of all product feature images. I am using woocommercee to generate an online shop and it was working perfectly(HD thumbnails image qualities), I also updated the woocommerce plugin but still getting low quality images on the products Can you please let me know why this is happening? Thanks
This happened to me. I installed a thumbnail regenerater plugin, this seemed to do the job for me.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, post thumbnails, thumbnails, woocommerce offtopic" }
Two theme options pages for a theme i am currently using a theme options page for a theme im building buti am looking to add another for advance settings. is there a way of doing this? Both would be using the same options would this casue a issue?
> is there a way of doing this? Yes, just go and do it? There is no inherent or implied limit to creating admin pages. > Both would be using the same options would this casue a issue? No, unless you code it in a way that it does. If both pages are going to be modifying same array of values (for example) they need to be careful not to blank or otherwise mangle each other's items.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
how to query multiple categories in wordpress? I am trying to query multiple category in wordpress but no luck, I don’t see anything wrong with my code. Herewith my code below : query_posts('posts_per_page=1&cat=5,1'); while ($wp_query->have_posts()) : $wp_query->the_post(); get_template_part('loop', 'single-home'); endwhile;
Use like this query_posts( array( 'category__in' => array(5,1), 'posts_per_page' => 1, 'orderby' => 'title', 'order' => 'ASC' ) ); or $my_query = new WP_query(array('category__and' => array(5,1))); while ($my_query->have_posts()) : $my_query->the_post();
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "query" }
How to only show posts on last child category By default WordPress will list posts on each category in its hierarchy. Example: Parent /- child /-- grandchild When viewing the "Parent" category you will see a list of posts from child, grandchild and parent - even if the post is just ticked in "Grandchild". My question is: How do I only show posts when viewing the last child? Is there a built in WordPress function for this? e.g.: [grandchild categories] = array of grandchildren if(in_array( [grandchild categories] )) : show posts else: do nothing
There is of course the `include_children` parameter for `WP_Query` as part of the taxonomy parameters. Which I suppose should work like this for you: $args = array( 'tax_query' => array( array( 'include_children' => false ), ), ); $query = new WP_Query( $args ); Or via `parse_tax_query` for your category archive: add_filter( 'parse_tax_query', 'wpse163572_do_not_include_children_in_category_archive_parse_tax_query' ); function wpse163572_do_not_include_children_in_category_archive_parse_tax_query( $query ) { if ( ! is_admin() && $query->is_main_query() && $query->is_category() ) { // as seen here: $query->tax_query->queries[0]['include_children'] = 0; } } _Note:_ Thanks to @PieterGoosen this is now tested and confirmed working.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "categories, hierarchical" }
What is the difference between wp_strip_all_tags and wp_filter_nohtml_kses? Taken from the articles referenced below: wp_strip_all_tags() "Properly strip all HTML tags including script and style." wp_filter_nohtml_kses() "Strips all of the HTML in the content." Ref: * < * < These functions _appear_ to serve the exact same purpose. How are they different?
The wp_strip_all_tags() function will remove all HTML, including the content of script and style tags. The PHP strip_tags() function largely does the same thing, except it won't eliminate the content of script and style tags. WP's wp_strip_all_tags() function uses this after eliminating the scripts and styles manually. The wp_filter_nohtml_kses() function uses kses to remove all HTML. The main difference is the engine used for parsing the HTML. PHP's strip_tags() doesn't deal particularly well with broken or intentionally malformed HTML, because it doesn't perform any validation of the HTML. The kses engine attempts to handle malformed HTML in a better way, but it is also not a fully complete HTML parser. It is also much slower. The wp_strip_all_tags() function is generally preferred. It's good enough for the majority of cases. The kses version is mostly included for completeness, but may be useful if you're dealing with particularly badly formed HTML.
stackexchange-wordpress
{ "answer_score": 14, "question_score": 10, "tags": "sanitization" }
Enable Full SSL for Wordpress I've enabled SSL for my main domain but i want to enable it fully for my wordpress website which is located in a subfolder. when i say fully i mean in admin area and the website itself and without any mixed content error. so first i tried adding these in wp-config: /* Enable SSL Encryption */ define(‘FORCE_SSL_LOGIN’, true); define(‘FORCE_SSL_ADMIN’, true); it resulted in getting mixed content error and "You do not have sufficient permissions to access this page" error after login to the dashboard. i got the same error when i tried to change the blog url and website url in settings. then i used plugins like "https-ssl", "fix mixed content". they didn't do anything good for me either. i'm looking for a way to make that happen
I had the same problem and solved it by moving the two define statements up before the require_once that includes wp-settings.php. Seems this was the issue all along. Source: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, wp config, ssl, https" }
Create menu without admin panel I am wondering where I can create menus without using the admin panel, or if it is a waste of time. In admin you can go to Appearance => Menus Where you can select a number of pages to add to the menu, select if it is the primary navigation in the theme etc etc I assume these menus are simply stored in the wp database (since they contain links to wp pages, also stored in the database?) If they are indeed stored in the database as opposed to templates, is what I am asking a waste of time? I assume I would have to look up the page id of the pages I would want to link to and these may be hardcoded?
Try this link may helpful < // Check if the menu exists $menu_exists = wp_get_nav_menu_object( $menu_name ); // If it doesn't exist, let's create it. if( !$menu_exists){ $menu_id = wp_create_nav_menu($menu_name); // Set up default menu items wp_update_nav_menu_item($menu_id, 0, array( 'menu-item-title' => __('Home'), 'menu-item-classes' => 'home', 'menu-item-url' => home_url( '/' ), 'menu-item-status' => 'publish')); wp_update_nav_menu_item($menu_id, 0, array( 'menu-item-title' => __('Custom Page'), 'menu-item-url' => home_url( '/custom/' ), 'menu-item-status' => 'publish')); } Hope it may help :)
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "menus" }
Change WordPress Multisite Domain I created a multisite install on a development domain. Now, I want to change it over to my main domain. I've heard that I shouldn't do a database dump, and change everything with a text editor. I've followed the WPEngine tutorial below, but it caused 500 server errors. Any advice? < Thanks, -Marc
When I move domains and have to change the domain in the database, I use interconnectit's Search and Replace tool. Here is a very brief overview of the process. 1. Export the database and upload it to the new server. 2. Upload interconnectit's Search and Replace tool to the new server. 3. Configure what I want to be replaced in the databases with the tool's GUI 4. Click "run" and that's it. You can find installation details and support over at the project's GitHub page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, domain mapping, phpmyadmin" }
Post/page title to permalink transformation - what is behind the scenes? If the post name is used as the permalink, what "transformations" does Wordpress do to it when using it as the URL and when does it perform these transformations? Like stropping spaces and special characters, etc. Thanks for explaining that process.
WordPress uses `sanitize_title` to create the URL-friendly version of titles for use as post slugs, which has `sanitize_title_with_dashes` hooked to the `sanitize_title` filter. You can see `sanitize_title` in use in source for `wp_insert_post` here, and `sanitize_title_with_dashes` in source here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, permalinks, pages" }
accessing my mu-plugins from within a template file I have created an XML files that use the same database as WordPress but largely non-WordPress content. I have had these XML files work as RSS feeds on an external domain, but would like to bring this inside of WordPress. I've created 4 custom feed-name.php templates, include my code and added them to WordPress with the filters etc. they currently return no content because I am unable to access WordPress's functions or my classes in my mu-plugins. My code includes `include('./wp-load.php');` which should allow access to WordPress's functions and my own, but this isn't working. Have i missed something? note: including `get_header();` breaks the page because it includes loads of html that doesn't validate as xml. p.s. no custom-template tag?
turns out a minor typo in a method call within a method in the class was causing some confusion. feeds have to be added to the init action too 1. function to create feeds 2. function to add actions 3. function to init actions function solved.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rss, xml" }
Multisite - One user allowed access to all sites? I am creating a multisite environment where each site is a classroom blog in the same school. Is it possible to create one parent user with access to all sites? That way parents don't have to keep logging in if they have students in different classrooms. If that is possible, the next question is, can I set up that parent user account with editor access on all sites? Or read-only access? I can't be the first person to create a group of classroom blogs like this. Any general advice would be appreciated!
You should be able to do this using the `Wordpress MU Domain Mapping` plugin. I've just tested this and it seems to work if I go to the `main` site and login I'm then logged in on all the sub sites. I think you might need to tweek the `domain options` for the plugin under `wp-admin/network/settings.php?page=dm_admin_page` for this to work. **_Reference_** WordPress MU Domain Mapping Single Sign On to all sites in my entire WP Network
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, users" }
Keep Title and Description always I want to keep the title and description of wordpress blog like this: Title | Description (showed in a tab of navigator). And I don't want to change his name while I am surfing the site. I think that changing a little header.php could be solution but is bad option change a file directly. Only I know that title is here: Any idea or advice?
In any properly coded theme the title should be completely generated with `wp_title()` and easily filterable to specific string (in `functions.php` or otherwise): add_filter( 'wp_title', function () { return get_bloginfo( 'name' ) . ' | ' . get_bloginfo( 'description' ); } );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "customization, title, wp title" }
the title not working from a custom post type I am trying to show a list of the latest 3 custom post types in the footer, and while I am getting the permalink ok for the href, the title is not displaying. Here is the code I put in the footer: $postslist = get_posts('numberposts=3&order=DESC&orderby=date&post_type=class'); foreach ($postslist as $post) : setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?> A plugin is generating the post type.
you need the WP_Query Before your Code: <?php $allCat = array( 'posts_per_page' => 3, 'tax_query' => array( array( 'taxonomy' => 'category-products', 'field' => 'slug', 'terms' => 'your-slug', ) ) ); ?> <?php $all_product = new WP_Query($allCat); ?> <?php if($all_product -> have_posts()) : ?> <?php while($all_product -> have_posts()) : $all_product -> the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
How to check if a post belongs to a category that has only 1 posts? Although I've done some searches on Google, I have not found an answer to this question: Is there a way to check if a post belongs to a category that has only 1 posts (is the only one in its category)? I need to perform this check on `single.php`. if ( 'the_magic_check' ) { // do something } Thanks!
Use `get_the_category` to get the categories belonging to the post. You can then use `$category->count` to return the amount of posts for specific category attached to the post Example: If a post has just one category attached to it, you can do the following $category = get_the_category(); echo $category[0]->count; In your check to see if there is only one post in the specific category and then do something, you can try if( 1 == $category[0]->count ) { // Do something if the category has one post only }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories" }
How to make blog post entries appear as input form instead of just text? I want my blog posts to appear inside of a form input box instead of just text on a page. Not the title, but only the submission. Is that possible. My index.php: <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><b><?php the_title(); ?></b> = <div class="entry"> <?php the_content('Read more &raquo;'); ?> </div> </div> <?php endwhile; ?>
You probably want this: <form action="demo_form.php"> <textarea name="blogpost" readonly="readonly"> <?php the_content(); ?> </textarea> <input type="submit" value="Submit"> </form>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, forms, blog, text, input" }
How to Set Taxonomy Object Description? I noticed when dealing with Post Type Objects (Using `get_post_type_object();`) and Taxonomy Objects (Using `get_taxonomy();`) there's a property called "description". How do you set this description property for Taxonomy Objects? I don't see an option for it in `register_taxonomy();`, but I do see an option for it in `register_post_type();`.
> I don't see an option for it in `register_taxonomy()` It's not in Codex, but is fully supported: add_action( 'init', function() { register_taxonomy( 'foo', 'post', array( 'description' => 'Hi there!' ) ); $foo = get_taxonomy( 'foo' ); echo $foo->description; // output "Hi there!" });
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom post types, custom taxonomy, taxonomy, post type, oop" }
Are post ID's reliable? I understand that post ID's are unique, but are they _reliable_ as persistent data ID's? More specifically, is there a guarantee that, through a migration or another data exchange, post ID's will not change? I understand wordpress is primarily implemented using MySQL, so ID's are governed by the `AUTO_INCREMENT` mechanism; however, is there any caveat on Wordpress' end that would change this behavior in the future, or potentially with another persistence implementation (such as MongoDB)?
The pedantic answer is NO. While IDs are unique they can change without any change in UX as long as the change retains the consistency of the DB. And while creating a new post will generate a new unique ID, you can also create a post via code to reuse some "old" ID. In practice they are reliable, but if reliability is very important to you then you need to attach some data to the post which will be used as the reliable identifier for your own needs. **Update:** totally forgot about it because it is rarely used, and most of the time I seen it used it was used incorrectly, but wordpress has a reliable unique identifier by definition and it is the GUID
stackexchange-wordpress
{ "answer_score": 6, "question_score": 7, "tags": "posts, id" }
Sort custom taxonomy terms order by both count and name I am working on a custom taxonomy sorting to make popular terms. The requirement is to sort by popular posts by post count and also I need to sort terms by name to get it alphabetical order. Here is my code $args = array( 'hide_empty' => 0 , 'orderby' => 'count', 'orderby' => 'name', 'parent'=> $cat_main->term_id ); $terms = get_terms('question_type',$args); Another condition is that `orderby` `count` has to be `DESC` and `orderby` name has to be 'ASC' Any suggestions?
This won't be possible via the function itself or to be exact by just providing parameters/arguments. You have to do this via hooks to alter the default behavior, I think. You should take a closer look at at least two, they are: `get_terms_orderby` and/or `terms_clauses`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "custom taxonomy, sort" }
Translating my custom theme, always translated version? I have a custom theme which is in Dutch and now i am trying to translate the theme into english. For this i am using poedit, and converted some theme strings into _e('string-is-here') I save both en_US.po and en_US.mo into my-theme/languages and add this to functions.php function theme_init(){ load_theme_textdomain('my-theme', get_template_directory() . '/languages'); } add_action ('init', 'theme_init'); to test it i edit wp-config.php by define('WPLANG', 'en_US'); And i thought it was working, but when i changed WP_LANG back to define('WPLANG', ''); The translated strings are always shown??? What am i overlooking? regards
You are making wrong assumption here. `define('WPLANG', '');` doesn't mean "original locale of the string" or anything like that, it is taken literally as "no locale specified". And when it's nothing WP proceeds to assume default locale, which is `en_US`. This is why as soon as you add English translations of string they are displayed for this case. So to test your original Dutch strings properly you need to set `WPLANG` to respective Dutch locale.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multi language, translation" }
Any required callbacks to WP.com or WP.org? China is blocking both WP.com and WP.org. I would like to know if WP4.0 includes any callbacks or references to files such as javascript libraries located on these domains, because I must plan for mainland Chinese users not being able to access them.
It is a little hard to quickly audit WP code base for wordpress.org links, because they are extensively used in inline documentation. On top of my head the main (if not only) requests are probably to `api.wordpress.org` for updates. For resources WP generally only uses bundled assets. The two notable exceptions are: 1. Deprecated libraries (such as prototype), which aren't used in core anymore. They are registered to load from `ajax.googleapis.com` and no longer bundled. 2. Web fonts in admin which aren't bundled because of technical challenges. They are registered to load from `fonts.googleapis.com`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "javascript" }
Filtered by a custom field, ordered by another I am trying to loop custom post-types, filtered by a custom field `artist-status => invited` and ordered by another custom field `last-name` alphabetically. Here is what I managed to write, and it doesn’t work as I need: $args = array( 'post_type' => 'artist', 'posts_per_page' => -1, 'meta_key' => 'artist-status', 'meta_value' => 'invited' 'orderby' => 'meta_value_num', 'order' => 'ASC', 'meta_query' => array ( array( 'key' => 'last-name') ) ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post();
You are sorting it incorrectly. You will need to check for `artist-status` meta key with `meta_query` and sort by `last-name` metakey. Here is your query. $args = array( 'post_type' => 'artist', 'posts_per_page' => -1, 'meta_key' => 'last-name', 'orderby' => 'meta_value', 'order' => 'ASC', 'meta_query' => array ( array( 'key' => 'artist-status', 'value' => 'invited', 'compare' => '=', ) ) ); $loop = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom field, order" }
Renamed my website (URL) – how do I rename all within-page links to the old URL? A while ago I renamed my website from ExplainingProgress.com to OurWorldInData.org . My problem is that sometimes – for some IFrames and some images – the URL that is linked to is still the old one (ExplainingProgress.com). An example are the IFrames on this page: < Is there a way of renaming all these internal links automatically or do I have to read through all the HTML and rename it by hand?
You can use a plugin called Velvet Blues Update URLs. I use it all the time. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, links, migration" }
Change sub-menu position of custom taxonomy I'm adding an additional taxonomy to the Posts post-type and would like it to appear between Categories and Tags in the control panel Posts sub-menu. I know when registering custom post types you can set the control panel menu position via the `menu_position` argument, but I can't find anything similar for custom taxonomies - they just seem to be added to the bottom of the list. Anyone know of a way to do this? Thanks!
Unluckily does not exist a clean way to do this, because register taxonomy doesn't provide a `menu_order` argument. But you can act on global `$submenu` variable and reorder it, something like add_action( 'admin_menu', function() { global $submenu; $found = FALSE; $before = $after = array(); $tax_slug = 'my_custom_tax'; // change your taxonomy name here foreach ( $submenu['edit.php'] as $item ) { if ( ! $found || $item[2] === 'edit-tags.php?taxonomy=' . $tax_slug ) { $before[] = $item; } else { $after[] = $item; } if( $item[2] === 'edit-tags.php?taxonomy=category' ) $found = TRUE; } $submenu['edit.php'] = array_values( array_merge( $before, $after ) ); }, 0 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy" }
How to display tag cloud without links How can a tag cloud generate a list of tags WITHOUT the links? This works fine for me, but I just don't want the links: wp_tag_cloud('smallest=10&largest=10&number=0&format=list'); Didn't see anything explicitly in here about this: < There are similar questions on here, but they have to do with tags for a particular post. I don't want the current page/post tags. I want all tags used on the site in a tag cloud. Display tags in list without link
We can modify the output with the filters `wp_tag_cloud` or `wp_generate_tag_cloud`. But we could also use: echo strip_tags( wp_tag_cloud( 'echo=0&smallest=10&largest=10&number=0&format=list' ), '<ul><li>' ); where we strip all the HTML tags from the output, except the `ul` and `li` tags. Notice that we added the `echo=0` parameter as mentioned in the Codex as a way to return the output. We could also have used `echo=` because it has to full fill the condition: if ( 'array' == $args['format'] || empty($args['echo']) ) to return the output. So `empty( null )` and `empty( '' )` is `true` but it's strange that `empty( 0 )` is also `true`, but that's just how the `empty()` function works ;-) The `wp_tag_cloud()` function has the `link` parameter, but it only has the possible values as _view_ or _edit_. It would be nice to have the _none_ option, to disable links and show only the text.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "tags, cloud" }
Get latest post from categories I have 3 categories: Travel, Destination and Tips. I've been trying to get the latest post from each categories then put them into an array. Here's what I have in mind. //GET CATEGORIES //I have this code but this only selects one category $args = array ( 'post_per_page' => 1, 'cat' => 16 ); //SELECT THE LATEST POST FROM EVERY CATEGORY //This part I don't know what to do. //GET ID OF THE POST SO THAT I CAN ADD IT TO THE ARRAY $post = array(); <-- This should contain every latest post from the categories. $post[] = get_post( /*ID OF THE POST SHOULD BE HERE*/ ); What I want to achieve is to have the id's of the latest posts from every category in the array. Please help. Thank you.
Ok you can use a foreach loop to return the latest post from each category. Here is how you should do that. <?php $postids = array(); $catids = array( 1, 2, 3 ); // add category ids here. foreach ( $catids as $catid ) { $my_query = new WP_Query( array( 'cat' => $catid, 'ignore_sticky_posts' => 1, 'posts_per_page' => 1, 'no_found_rows' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false ) ); if ( $my_query->have_posts() ) : while ( $my_query->have_posts() ) : $my_query->the_post(); $postids[] = $post->ID; endwhile; endif; wp_reset_postdata(); } print_r( $postids ); // printing the array. ?> It's practically the same as running the 3 different loops but code is much cleaner now.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, categories, array" }
Custom Post Type not visible on category page I would like to use the default category for my custom post type, but when I open the category page there's no posts there. The loop is very simple: <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div class="col-md-3 col-sm-6 col-xs-12 margin-bottom-30"> <?php $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'product' ); ?> <div class="item-image"><a href="<?php echo $large_image_url[0]; ?>" class="zoom-effect"><?php the_post_thumbnail('product', array( 'class' => 'img-full' )); ?></a></div> <div class="item-desc box-grey padding-all-10"><?php the_title(); ?></div> </div> <?php endwhile; else: ?> <p><?php _e('No posts were found. Sorry!'); ?></p> <?php endif; ?> I don't want to use custom taxonomy. I also created the archive-{cpt}.php file for displaying all posts. Where is the problem?
Custom post types are excluded from the main query by default (except on taxonomy pages and custom post type archive pages), that is why you don't see posts from your custom post type on your category page. You need to include your custom post type posts in the main query manually. That is done with `pre_get_posts` which alters the main query before it is executed. You can do the following to include your custom post type on category pages function custom_post_type_cat_filter($query) { if ( !is_admin() && $query->is_main_query() ) { if ($query->is_category()) { $query->set( 'post_type', array( 'post', 'YOUR CPT' ) ); } } } add_action('pre_get_posts','custom_post_type_cat_filter');
stackexchange-wordpress
{ "answer_score": 12, "question_score": 1, "tags": "custom post types, loop" }
Lost password and back to blog in same line I would like put on the same line "Lost your password?" and "Back to Blog/Site" links. While I'm posting that I take a look to this post and found my solution: Positioning the “Lost your password?” and “← Back to Site” I've posted that for if it helps someone.
My solution. I added via functions.php the following: function my_login_logo() { ?> <style type="text/css"> .login #backtoblog{ float: right; position: relative; top: -35px; } </style> <?php } add_action( 'login_enqueue_scripts', 'my_login_logo' ); That code move to right side and a little to top the 'Back to Blog/site' link. Hope that helps!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "customization, login" }
MySQL LIKE not working It seems MySQL's LIKE operator behaves like a = operator. The following MySQL query returns the expected result (1 entry): $meta_key = '_locality'; $meta_value = 'The Hague'; $post_ids = $wpdb->get_col( $wpdb->prepare( " SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value LIKE %s ", $meta_key, $meta_value ) ); But the following returns an empty array: $meta_key = '_locality'; $meta_value = 'The'; $post_ids = $wpdb->get_col( $wpdb->prepare( " SELECT post_id FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value LIKE %s ", $meta_key, $meta_value ) ); What am I doing wrong here?
Try to replace: AND meta_value LIKE %s with AND meta_value LIKE '%%%s%%' so your SQL will become: AND meta_value LIKE '%The%' instead of: AND meta_value LIKE 'The'
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "mysql, wpdb" }
change link of menu particular tab Wordpress theme - `Twenty Twelve.` I want to change link of menu. > Current --> No link. > > Required -->#about (link for particular tab only) I've tried to change link from `menu tab` (Apperance --> Menu) but no use. In header file I have this code: <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?> and In Manage location no menu is selected. ![enter image description here]( What to do?
It seems you have no menu selected. In the _Manage location_ screen select an existing menu and Save changes. If there is none, click on "Use new menu". Then you should be able to edit it in the _Edit Menus_ screen. See the Codex article on Menu Screens and the one on `wp_nav_menu`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, links, dashboard, theme twenty twelve" }
Remove the “View” Link in Post edit Admin add_filter( 'post_row_actions', 'remove_row_actions', 10, 1 ); function remove_row_actions( $actions ) { if( get_post_type() == 'my_cpt' ) unset( $actions['view'] ); return $actions; } This code removes the view link from post list, but I want to remove the link from post edit page also. Can anyone help ?
(1) The Edit Permalink HTML including the View-Post button is passed through the `get_sample_permalink_html` filter. You will likely have to `preg_replace()` the view post button out of it: function my_get_sample_permalink_html($a){ return preg_replace("/<span id='view-post-btn'>(.*)<\/span>/",'',$a); } add_filter('get_sample_permalink_html','my_get_sample_permalink_html'); (2) The message after a post has been updated can be altered by filtering `post_updated_messages`. Like this: function my_post_updated_messages( $messages ) { $messages['post'][1] = __('Post updated'); return $messages; } add_filter('post_updated_messages','my_post_updated_messages');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom post type archives" }
wp_create_nonce function doesn't work inside a plugin? I am writing a WordPress plugin which is creating a form in one of its functions. It looks like this (very simplyfied): class MyPlugin { public function createForm() { $nonce = wp_create_nonce('my_form_nonce'); echo '&lt;input type="hidden" value=" . $nonce . "&gt;'; } } This is not working. I get PHP error message function `wp_create_nonce` doesn't exist. Well I understand that there are not all WP functions available in my custom plugin class context. But how do I do this? How do I implement WP token security inside my plugin form? What is the common approach here?
`wp_create_nonce` is a pluggable function loaded after plugins are loaded. Be sure to call your class method on proper hook, `'init'` (or later) is a good place: once your function output something (a form) there is no reason to run earlier than that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin development, forms, security, nonce" }
How to create bulk page and content? I am creating a website about cars. I want to have a page for each car, with subpages (i.e. Gallery, Specs, etc...) for each car page. I have the content on my hard drive for each car. Doing this manually will take forever, so i was thinking of writing a code (maybe in python) that will fill the contents for each car into an html file; however, i read that Wordpress doesn't store files but instead keeps the content in a database. So my question is, what's the best way to create bulk pages and upload them to Wordpress? Is there a plugin which i'm missing that can do this? Thanks.
I would suggest manually creating your first page (a custom post type might make more sense here?) in WordPress and then use the fantastic WP CSV plugin to export the page. Using the first page fields as a guide, simply copy your car data into the appropriate cell in a chart and import the completed CSV data when finished.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "database, bulk, bulk import" }
Wordpress permalinks confusion I have just realised something that I never knew and I wanted to get confirmation that it is expected behaviour or whether the website I am working was behaving incorrectly. I creating a page - lets call it "page". Whenever I went to this page, I getting the following message: Directory Empty I then discovered I had a directory in the root Wordpress directory called "page" which was empty - so I deleted it and it worked. Is it correct that Apache will check locally first before allowing htaccess to process the Wordpress permalinks? Is this normal, expected behaviour?
It is the way the .htaccess wordpress generatea instructs apache to work on the wordpress directories The relevant parts from the default .htaccess RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] The first line will cause the rewrite engine to bail out if there is a file with the same name as the server is asked to serve The second line will cause the rewrite engine to bail out if there is a directory with the same name as the server is asked to serve The third line is what actually invokes wordpress and you will not get to it if you bailed out on one of the first two lines.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "htaccess, apache" }
How can I get a list of custom post IDs into a variable I can use for another function? How can I get the same output into a variable that I can then use in another function? //get all the post ids of current projects $qry_args = array( 'post_status' => 'publish', // optional 'post_type' => 'project', // 'posts_per_page' => -1, // ALL posts 'fields' => 'ids', ); $all_posts = new WP_Query( $qry_args ); foreach((array) $all_posts->posts as $id) { echo $id .','; } The above code works fine to create an "array" of IDs, but I need to be able to put it into a variable so I can then use it in another function like so: echo do_shortcode('[mla_gallery post_parent='. $ARRAYOFid .' posts_per_page=12]'); I know I am missing something easy here...
You can push all your individual id's from your `foreach` loop to a variable outside your `foreach` loop, like this ( _please note, this is not the preferred method as there is a simpler method, just scroll down_ ) $post_ids = []; foreach((array) $all_posts->posts as $id) { $post_ids[] = $id; } ?><pre><?php var_dump($post_ids); ?></pre><?php `$post_ids` will hold your array of id's Alternatively, which is actually the better and preferred method here, `$all_posts->posts` already holds an array of post ids, just assign that to a variable $post_ids = $all_posts->posts; ?><pre><?php var_dump($post_ids ); ?></pre><?php **EDIT** If you need a string of id's, you can just implode `$post_ids` $string_ids = implode( ',', $post_ids );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "array" }
the_content() behavior on attachment.php versus single.php I'm having some trouble getting `the_content()` to work on attachment.php. I have a template page that has the basic loop and simple calls `the_content()` in the loop to display the post. ## Scenario 1 Load an attachment page with the template file `single.php` and it will output the image tag and run it through `prepend_attachment`. ## Scenario 2 Load an attachment page with the template file `attachment.php` and it will output nothing from `the_content()`. I've also verified that it doesn't called the prepend_attachment or the_content filters. Can someone explain what is going on here? <?php if (have_posts()) : while (have_posts()) : the_post(); the_content(); endwhile; endif; ?>
This is correct behavior, if your attachment doesn't actually have anything in `post_content` field (which is quite common). When post–centric templates run, `prepend_attachment()` is used as filter to "emulate" post content. This is not the case with template "intended" for attachments. If you look at `template-loader.php`: elseif ( is_attachment() && $template = get_attachment_template() ) : remove_filter('the_content', 'prepend_attachment'); the filter is explicitly removed. So there is no "fake" content generated for you. You will have to decide and express in code what do you actually want shown for attachments, or simply add back the filter if _that_ is what you want.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "attachments, the content" }
Wordpress showing wrong category name I'm using: $category = get_the_category(); echo $category[0]->cat_name; to display the current category as a header in an archive template (example of local url is < < etc) For the first 3 categories, this works fine, but after that it's showing a child category instead. I've tried changing the slug of the posts _and_ the category, updating the permalinks, unpublishing posts in the child category which is showing (it then shows another child category instead) - but none of this solves the problem. I suppose it's a clash of slugs & permalinks somewhere, but changing these doesn't seem to fix it. Is there more specific wordpress php which can be written to avoid this clashing? I did find this post: Archived Posts in Wrong Category but it doesn't seem to be the same problem. Thanks
As far a I can understand you need to display the category name for the current page when viewing a category page. You can make use of the query variables to retrieve the category name, for example: $category = get_queried_object('cat');  echo $category->name; **EDIT** A global check to see what is returned by the main query for a specific page/template, you can do a `var_dump` of the main query global, `$wp_query`. Add the following code inside your template outside of the loop ?><pre><?php var_dump($wp_query); ?></pre><?php To check which query variables are available on a template/page, you can do a `var_dump` of `get_queried_object()` $queried_object = get_queried_object(); var_dump( $queried_object ); Here is also a list of all query variables
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, archives" }
How to enqueue a random css style? I want a random CSS style file to load on my site with each page view so I can play with colors backgrounds. So I put all my styles in a folder, I named them `1.css`, `2.css`, etc. and I have added: <link rel='stylesheet' id='name-random-color-css' href=' echo mt_rand(1, 9) ?>.css' type='text/css' media='all' /> in the header. It works but I know this is not the proper way to include styles in WordPress. I should utilize the `wp_enqueue_style` function in the `functions.php` file, but I don't know how to combine the two to make it work.
This should work! function enqueue_random_style() { wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/inc/rcolor/' . mt_rand(1, 9)); } add_action( 'wp_enqueue_scripts', 'enqueue_random_style' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "css, wp enqueue style" }
Getting the parent terms adds additional empty markup I am trying to get only top level terms from hierarchical taxonomy called "City". It works fine in a way, because it outputs extra elements... $cities = get_terms( 'city' , array( 'parent' => 0, 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => true )); foreach ($cities as $city) { ?> <li><a href="<?php echo get_term_link( $city, 'city' ); ?>" class="button radius"><?php echo $city->name; ?></a><li> <?php } ?> </ul> Which retuns only 2 cities (and each of them has several child terms) The returned HTML looks like this: <li> ... correct data about term 1 </li> <li> </li> <li> ... correct data about term 2 </li> <li> </li> </ul>
check your closing * your missing the close. It should be <li><a href=""></a></li>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, html, terms" }
Load slideshow.css file only if Slideshow is checked / on I use <?php if ( get_option('mytheme_slider') == 'checked') { get_template_part( 'partials/slider/slider-java-script' ); } ?> to include the slider-java-script.php template part into my site. Works fine. How can i include or load my **slider-java-script.css** file if the same option is checked?
Add a function to your functions.php file like this: function slider_scripts() { wp_enqueue_style( 'slider-java-script', get_template_directory_uri() . '/css/slider-java-script.css' ); //change the location to work for you } Then add slider_scripts() to the top of the template part ( partials/slider/slider-java-script.php )
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, functions, theme development, css, conditional tags" }
Bulk update post slugs through database Is there a way to bulk update permalinks through the database? cause I have like 20k posts and all I want to do is add a prefix to the permalink. I could just manually update but that's too tiresome for 20k posts. For example if post url is ` I want to change it to `
Try this query, remembering to change out `your_posts_table` with the proper name in your database. Using `CONCAT`, you can add any number of strings, just pass `post_name` to add your changes before/after. update your_posts_table set post_name = CONCAT('pre-', post_name) * More info on MySQL CONCAT * **Note:** Use a `WHERE` clause if you only want to update specific posts.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, permalinks, slug, sql" }
Outputting query results I am trying to make plugin, and i followed codex, i am not a OOP literate, hence i a blank. I tried to run this query `$myrows = $wpdb->get_results( "SELECT question FROM wp_quiz" );` while i tried to echo $myrows but it didn't gave me anything, so i tried to `print_r($myrows)`, which gave me my output with the following prepend text > Array ( [0] => stdClass Object ( [question] => What is the flag color of Pakistan ) ) How can i echo out a proper column from the table, because i just seemed to start.? Do i need to do crash course on OOP before getting into this? What should i know.?
By default, wordpress get_results return a numerically array of objects, so to use echo to print your data yo should do something like; foreach($myrows as $line){ echo $line->question; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, wpdb" }
check if the user is owner of current page I am struggling with this little problem. I have a user profile page and I want to change some of the content based on whether it is my own profile og someone elses. This is my code to add a shortcode which eventually will call other shortcodes. function is_mine_func() { if (is_author() ) { echo 'it is my site'; // echo do_shortcode('[wpfepp_submission_form form="2"]' ); } else { echo 'its not your site'; //echo do_shortcode('[userpro template=postsbyuser postsbyuser_mode=grid]' ); } } add_shortcode( 'minminmin', 'is_mine_func' ); I have a feeling that is_author is not the right way to do so since I always get the 'its not your site' message no matter if I am the author of the page or not. Should is_author() not evaluate if I am the author of 'this' page or not?
Per the Codex, `is_author()` checks to see if you're on an Author Archive page (ie, a page listing all the posts/pages/etc that a given user has authored). If you're on any other type of page, `is_author()` will return `false`. What you're looking for sounds more along these lines: if ( in_the_loop() ) { get_currentuserinfo(); print ( get_the_author() === $GLOBALS['current_user']->display_name ) ? 'It is my site.' : 'It is not my site.'; } This code must be used in The Loop. ## References * `is_author()` * `get_the_author()` * `get_currentuserinfo()` * `in_the_loop()`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, shortcode" }
Create page using same slug as custom post type I am working on a site for a client who has custom post type called "practitioners" and several posts within this displaying info related to different practitioners. I want to create a page with a slug "practitioners/page-name" but of course the site wont let me use this as a slug. I tried creating a parent-page called practitioners (which wouldnt be used) and then a child-page with the slug "practitioners/page-name" and the slug worked fine, but then when I view the page I get "nothing found" because there is no practitioner called page-name. Any ideas? Thanks
I got the client to agree to a slightly different slug so that all the CPT's pages used a parent of "practitioners" and the pages I was trying to create could use "practitioner" without the S, it simplified things alot and users may not notice or even care!
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "custom post types, slug" }
WPDB Prepared Delete I am attempting to delete a row from my DB.I am using inputs from the user and I need to be able to sanitize using the prepared statement. The query itself looks like - DELETE FROM wp_thing_assignment WHERE (account_number,user) values (1, 'DudeDev') I am using the following code - $success = $this->wpdb->query($this->wpdb->prepare( "DELETE FROM $this->table_name WHERE (account_number,user) values (%d, %s)", array ( $this->company[$i], $this->employee) )); I get this error - > You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'values (1, 'USER')' at line 1 Is there any way to salvage this query?
I think you have just confused syntax with INSERT :) According to manual the DELETE syntax is: DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name [PARTITION (partition_name,...)] [WHERE where_condition] [ORDER BY ...] [LIMIT row_count] No `VALUES`. Rather than forming this query manually you should consider using `$wpdb->delete()` helper.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wpdb" }
How to upload unknown file type? I've already read about mime types in wordress and how to add them, but I can't find any documentation about the `correct type` of files. For e.g. after a lot of research I find out that the **epub** extension has a **application/epub+zip** file type, but how to get other unknown files like `.blend` or `.xcf` to work? The following pseudocode illustrates the problem: function custom_mime_types($mime_types){ //Adding unknown extension $mime_types['unknownextension'] = 'typeoffile'; return $mime_types; } add_filter('upload_mimes', 'custom_mime_types', 1, 1); Is there a Documentation about it?
You can use this function as you mentioned and you need to learn your file extensions mime type (in example i add svg and xcf upload ability to wordpress) add_filter('upload_mimes', 'ability_to_upload'); function ability_to_upload($mimes = array()) { $mimes['svg'] = 'image/svg+xml'; $mimes['xcf'] = 'image/xcf'; return $mimes; } Here is a link for mime types list and file extension checker (you can search by file extension)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "uploads, media library" }
Get all post from table and put it in excel sheet I have website with 25025 posts, And i need to get the post name and the post url for all post in 2014. and export it in Excel sheet. How can i do that. i try to do this query but i dont get the URL of post and get all post in 2014 $querystr = " SELECT $wpdb->posts.* FROM $wpdb->posts, $wpdb->postmeta WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' AND $wpdb->posts.post_date < NOW() ORDER BY $wpdb->posts.post_date DESC ";
Here's the SQL I used to create this view in phpMyAdmin. Since you cannot get the permalink URL out of the database we have to pull the GUID. This link does in fact get you to your post, since it uses the unique ID of the post. SELECT `post_name`, `guid` FROM `YOUR_TABLE` WHERE `post_date` >= DATE('2014-01-01') ORDER BY `post_date` DESC For all of the data in your posts table use: SELECT * FROM `YOUR_TABLE` WHERE `post_date` >= DATE('2014-01-01') ORDER BY `post_date` DESC
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "export" }
Use a Wordpress Plugin in non-Wordpress .php page I have a website consisting of html pages but with one blog page in Wordpress. There is a news ticker plugin on this wp page which I would like to embed into the other pages of the site. How can this be done? Many thanks in advance.
Well...outside of the fact that you're unable to load PHP in *.html files, let's try to look at this from a different angle here... One way that this could be done would be to convert all of the *.html pages - that you would like to include the news ticker on - to *.php pages, and to insert a PHP function that loads WordPress in the header of those files, along with the news ticker shortcode or display function. Another way that this could be done would be to create one .php file in the root of your WordPress installation that only includes the aforementioned PHP function that loads WordPress in the header of that one file, along with the news ticker shortcode or display function, and loading that on the html pages through an iFrame. Here's the function I referenced above: To include WordPress in an external .php file, place the following code in the header of the file.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins" }
How to get post id of static front page? I'm trying to use the front page as a default of sorts for featured images (if no featured image is set, I want to use the front page's, for example) But I'm having trouble finding out how to get the post ID of the front page in a safe manner (so that my code still works when the front page is inevitably changed by someone) I know I could just hard code an ID in my code, but that'll break when someone decides to use a new content item as the front page. Would I have to use wp-query to achieve this? And if so, what is a safe way to achieve this with wp-query?
WordPress has a few useful options. You can get the homepage ID by using the following: $frontpage_id = get_option( 'page_on_front' ); or the blog ID by using: $blog_id = get_option( 'page_for_posts' ); Here's a list of many useful `get_option` parameters.
stackexchange-wordpress
{ "answer_score": 103, "question_score": 48, "tags": "wp query, homepage" }
Uploading video to vimeo using its API while bypassing php server limits I have a code that uses vimeo upload API to submit video files to vimeo using a form in a WorpPress site. The process works fine as long as the video file size is below the file upload limit of the web server. Is there a way in the vimeo upload API to bypass any of the file upload limitations of my web server and use a direct approach to upload the video file to vimeo?
Vimeo's simple POST uploader goes right from the client to vimeo's servers. Check out the documentation here : <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "vimeo" }
Using a Single Custom Post Type Template for Multiple CPTs I'm working on a major WordPress site and ran into a problem where I need to use multiple custom post types, but I only want to use one template for all of them. I found a code by Brad Dalton of WPSites that works with a single CPT name. Looking for a solution that allows multiple CPTs. Source: < What I want is the ability to use cpt-1, cpt-2, cpt-3. I'm not a PHP coder, not quite sure how to make this an array that will work in my functions.php BTW, I wish there was a `is_post_type_single` like there is a `is_post_type_archive`. Would be much easier to default to all CPT Single templates. Editing Reasons: Removed Brad's code to respect his copyright. Added link to source.
Doesn't exist any `is_post_type_single` function, because there is no need for it. `is_singular()` fit perfectly your purpose. Example code using `'template_include'` filter: add_filter( 'template_include', function( $template ) { if ( is_singular( array( 'cpt-1', 'cpt-2', 'cpt-3' ) ) ) { $locate = locate_template( 'custom-template.php', false, false ); if ( ! empty( $locate ) ) { $template = $locate; } } return $template; }); Of course change the name of your CPTs and the name of your custom template. Please note that you haven't to use the full path of template, just its name, but the file need to be in child theme or parent theme folder.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
How to assign a div class to a echo function How can I assign a CSS (span or div) class to this function, so that I can style the output in my style sheet? function show_today_date() { echo date(get_option('date_format')); } add_shortcode( 'showtodaydate', 'show_today_date' ); The result is **15 October, 2014**. Now I wish to style the output, which won't be possible if I do not have a CSS element.
This is not a specific WordPress question, is a topic in php coding. You can add html markup inside the echo in your function, like the follow example: function show_today_date() { echo '<div class="example">' . date( get_option( 'date_format' ) ) . '</div>'; } add_shortcode( 'showtodaydate', 'show_today_date' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "functions" }
Different Front page for Mobile I want to make a different front-page and show it to the mobile user, instead of the one used on desktop. In detail, right now we have set our site to show desktop-front-page to user, when he lands on www.domain.com. Now, I want to make a different front-page (mobile-front-page) which can be served to the user coming from mobile. Is that possible? Any ideas? PS. I looked into `wp_is_mobile()` but that seems to send mobile user to a URL you specify. What I actually need is that user should land (and remain) on www.domain.com, but instead of the desktop-front-page, the mobile-front-page should be served.
Switching the actual template file could work in the same way as above using `get_template_part()`. For example... <?php if ( wp_is_mobile() ) { // If it is a mobile device get_template_part( 'mobile-front', 'page' ); } else { // If it is not a mobile device get_template_part( 'desktop-front', 'page' ); } // end wp_is_mobile() To take this a step further... You could add a filter on `template_include` to load the specific template file using `wp_is_mobile()` to determine which template file to load. The Codex info for `template_include`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "options, mobile, frontpage" }
Query all posts with specific tag I need to fetch all the posts with a specific tag, but I'm getting all the posts instead. My query works if I publish a post with the tag that I need and list all the posts with that tag, but when I publish a post with another tag, it's fetching the newly published post. This is my query: $original_query = $wp_query; $wp_query = null; $args=array( 'posts_per_page' => -1, 'tag' => $post_tag ); $wp_query = new WP_Query( $args ); $post_titles=array(); $i=0; if ( have_posts() ) : while (have_posts()) : the_post(); $post_titles[$i]=get_the_ID() ; $i++; endwhile; endif; $wp_query = null; $wp_query = $original_query; wp_reset_postdata();
It's a lot easier to create a new WP_Query than it is to try clearing or overwriting the original. If $post_tag is a tag slug, you could simply use: <?php $the_query = new WP_Query( 'tag='.$post_tag ); if ( $the_query->have_posts() ) { echo '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li>' . get_the_title() . '</li>'; } echo '</ul>'; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "tags" }
Adding a filter with custom function to the menu / navigation I'm going to get crazy with the problem: I want to add a specific css class to the menu items, depending on a custom taxonomy. This is my code so far. add_filter('nav_menu_css_class', 'auto_custom_type_class', 10, 2 ); function auto_custom_type_class($classes, $item) { if($item->object == "marke") { if( has_term( "laden-1", "laden", $item->ID ) ) { $classes []= "laden-1"; } } return $classes; } First I check, if the post type is "marke" After that I check, if the "marke" has the characteristics "laden-1" at the taxonomy "laden". After about three hours I think, that there is a problem with the function "has_term", It seems that this function is not called correctly. Does anybody has a suggestion? Many many thanks in advance
I'm not sure how you're settings up your menus but this is probably the most reliable method. function auto_custom_type_class( $classes, $item ) { $type = get_post_type( $item->object_id ); if( $type == "marke" && has_term( "laden-1", "laden", $item->object_id ) ) { $classes []= "laden-1"; } return $classes; } add_filter('nav_menu_css_class', 'auto_custom_type_class', 10, 2 ); The problem with your code is that `$item->ID` refers the to the navigational items ID instead of the actual post ID which is found at `$item->object_id`. Using the ID to get the post type is probably more reliable than checking `$item->object` though you may be able to use that method.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, menus" }
Is there any advantage to emptying comment spam? Is there any advantage to performance (or otherwise) for emptying comment spam from within wp-admin on any regular basis? I daily have been making sure that the comment spam queue is emptied out, but is this serving any purpose?
There is definitely a performance advantage in keeping your comment spam to a minimum. If you have a lot of comments, the query time can get pretty out of control. To make it easier, you should install Akismet if you haven't already. Akismet will automatically detect spam comments and move them to WordPress spam section. You can then delete all the spam comments in one click, _OR_ you can change the default empty trash days from 30 days to something much sooner. If so, you'll want to add the following to your wp-config.php file: define( 'EMPTY_TRASH_DAYS', 1 ); And if you're brave and would like to just delete spam comments (and everything else in the trash) without sending them to the trash, you can add the following to your wp-config.php file: define( 'EMPTY_TRASH_DAYS', 0 );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "comments, spam" }
Error on update translation I installed a fresh version of WordPress in my current language (pt_BR) on localhost (WAMP). After log in, WordPress told me that exist an translation update. I clicked to update and the following message appeared: Atualizando traduções de WordPress (pt_BR)… O pacote não pôde ser instalado. PCLZIP_ERR_BAD_FORMAT (-10) : Unable to find End of Central Dir Record signature Translation Upgrading Translations of WordPress (pt_BR)… The Package : can not be installed. PCLZIP_ERR_BAD_FORMAT (-10) : Unable to find End of Central Dir Record signature I try to update language files manually , but the update indicator keep popping up
Found answer here: < wampmanager -> PHP -> PHP Extensions -> php_zip
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "updates, installation, translation, localhost, local installation" }
wp_logout_url($redirect); is not working in wordpress I am writing a simple WP plugin that could log the user in and out. As far as login is concerned its working good but I cannot log out, through my plugin. Logout doesn't work after I login. I have tried a lot of suggested solutions but none of them worked. This is my code: function vrm_loginout(){ if(is_user_logged_in()){ echo '<a href="<?php echo wp_logout_url($redirect); ?>" title="Logout">Logout</a>'; //tried following as well //echo '<a href="<?php echo wp_logout_url( get_permalink() )>" title="Logout">Logout</ a>'; title="Logout">Logout</a>'; }else{ wp_login_form(); }//end of if }//end of function add_shortcode('vrm_loginform', 'vrm_loginout');
You are using PHP tag inside echo statement. Try this: echo '<a href="'.wp_logout_url().'" title="Logout">Logout</a>'; If you want to redirect to any specific url then you can pass it as argument of `wp_logout_url`. Check official documentation of `wp_logout_url`. **Note :** It is recommended to return value from the shortcode function rather than directly displaying it. Try `return` instead of printing output by `echo`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, user registration, logout" }
Can you change the main heading of a page in the WordPress admin (without output buffering or JavaScript)? I'd like to change the heading text on an edit page—this bit: !wp admin screenshot I'm currently targeting it with jQuery (`.wrap h2:first-of-type`) and rewriting it that way, but it's not totally elegant - there's a bit of a flash when the page first loads that I'd like to avoid. I know I could register a custom post type and set those titles manually (the `labels` attribute), but I'd only like it to change when certain conditions are met, and I'd like to change it to use information saved elsewhere in the site. I'd like to avoid output buffering as well. From what I can tell, core is just echoing `$post_type_object->labels->name` \- is there any way to filter that output? I can't find anything, but I may be looking in the wrong places. Thanks!
Found it! The `post_type_labels_{$post_type}` filter does the job beautifully. (Documented here.)
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "wp admin" }
meaning of (array)function() I saw this piece of code that have part of the code I never saw before. What is the behavior of (array) in this scenario? so far I know the way of creating arrays in php never see this. // $this->settings = array_merge( $this->settings_defaults(), (array) get_option( $this->settings_slug, $this->settings_defaults() ) ); //
You are looking at type casting: < What the code does is caste the value returned by `get_option()` to an array. It is being done so that `array_merge()` works correctly and doesn't trigger warnings/errors. That much is pure PHP and is off-topic. The only reason I chose to answer rather than to post a comment is because the return value of `get_option()` will return various types of data depending on context. You can see that noted in the source: > @param bool|mixed $pre_option Value to return instead of the option value. > > < That means that you have to manipulate the return data in order to be sure of the type of data that you are dealing with.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, functions, array" }
When and Where is `global $post` Set and Available? Usually when people think of the `global $post` object it's assumed that it's actually set whenever you enter The Loop. I started to play around with how early I could actually call `global $post` which looks like: before `wp_head()` in most `header.php` files before `template_redirect` action after `plugins_loaded` So my question is, what's the earliest I have access to `global $post`?
Global `$post` var is set by `WP::register_globals()` method. It is called by `WP::main()` method, on its turn called by `wp()` function that is called when `wp-blog-header.php` is loaded. If you look at the graph **@Rarst** built, on the left, you can see where `wp()` function is called. In terms of hooks, global post variable is set just before `"wp"` hook runs, so that is first hook to be safely used to check it.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 5, "tags": "posts, globals, oop" }
Post slugs and images cannot have same name? If I go to Media Library and upload an image called `apple-pie.jpg` And then I create a post called `www.domain.com/apple-pie/` The link does NOT take me to the post. Instead the link will take me to a page displaying the media (In other words, it uses a page template instead of single.php) So does Wordpress NOT allow images and post slugs to be the same? How do I fix this problem? Do I have to rename all of my images?
WordPress uses the attachment filename to create the attachment post slug. If your file was named something else, there would not be any conflicts. If you have your post permalinks set to `/%postname%/` , and you upload an image FIRST, and then create a post SECOND, then WordPress has to make a choice between the two when someone tries to access the Permalink. To solve the issue, you would either have to change your permalink structure OR change the name of either the post or the attachment.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "posts, permalinks, images, media library, slug" }
Where does wordpress store the FTP credentials? When wordpress asks for FTP information to upgrade, you type it in and then it seems to store it for future use (for future upgrades, and maybe also for media uploads?) Where does it store these details? Is it in a file? In the database? I'm trying to figure out what information is being used to access the server. Tried grep-ing for `ftp` in the php files and didnt see anything. This also doesn't seem to be a setting that is exposed in the admin interface. Thanks!
It doesn't. WP Filesystem API will ask for FTP credentials, but it will do so for each operation. They aren't stored persistently. They _can_ be stored persistently by hardcoding into `wp-config.php`, but WP won't do that itself, it's a user action. Note that WP only asks for FTP credentials _if_ it cannot modify files without them. If specific setup used to ask for them and stopped then likely the server configuration or file permissions had changed and now allow WP to manipulate files without going through FTP.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "uploads, ftp" }
How to check if a user exists by a given id Is there any way to check if a user id exists? I want to create a function similar to `username_exists()` but which returns if the id exists or not.
Use this function: function user_id_exists($user){ global $wpdb; $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->users WHERE ID = %d", $user)); if($count == 1){ return true; }else{ return false; } } Usage: if(user_id_exists(1)){ //it does exists } else { //it doesn't }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 15, "tags": "functions, users" }
Shortcode from admin textarea to page I've added shortcode to a page via a custom textarea in my Wordpress admin, but the shortcode is seen as text and gets wrapped in quotation marks, so it doesn't work. !enter image description here This is basically how I sanitize my input: if( isset( $input['textarea_input'] ) ) $new_input['textarea_input'] = sanitize_text_field( $input['textarea_input'] ); This is how I output it on the page: <?php echo $options['textarea_input']; ?> do_shortcode does not change anything <?php echo do_shortcode($options['textarea_input']); ?> My guess is that the Wordpress TinyMCE editor recognizes shortcode, and therefor it works. Since mine is added via a hidden text area, it's just seen as plain text. What is going wrong here?
Your sort of right, the Wordpress editor saves content thru a filter called the_content. This filter is used to filter the content of the post after it is retrieved from the database and before it is printed to the screen. Apply this filter to simulate TinyMCE formatting. <?php echo apply_filters( 'the_content', $options['textarea_input']); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, tinymce" }
get all levels parents from id term I have a term referenced by $id. The term is inside a tree of levels. rootlevel parent (parent=0) first level parent second level parent ... ... last level parent many terms, my term $id How can I get all the parents: root level, first level, second level ..., last level parent of my term?
You can get all of the parents of an object via `get_ancestors` - $term_id = 42; $your_taxonomy = 'sometax'; $parents = get_ancestors( $term_id, $your_taxonomy );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 0, "tags": "hierarchical, advanced taxonomy queries" }
Adding menu_order to CPT admin page I have a custom post type (cpt_roundtable), and am trying to add a column to the admin page showing the menu_order for each entry. This is in my functions.php file. function set_roundtable_columns($columns) { return array( 'cb' => '<input type="checkbox" />', 'title' => __('Title'), 'taxonomy-sessions' => __('Session'), 'menu_order' => __('Order'), 'date' => __('Date'), ); } add_filter('manage_cpt_roundtable_posts_columns' , 'set_roundtable_columns'); It works perfectly except that the 'Order" column does not populate. I guess I have the incorrect term name for that field(?) Do I have to write a function to populate this column even though it's not a custom field?
Yes, you need to write code to populate it. This is untested but should work. add_filter('manage_edit-cpt_roundtable_columns', 'init_roundtable_custom_columns'); function init_roundtable_custom_columns($columns) { return array( 'cb' => '<input type="checkbox" />', 'title' => __('Title'), 'taxonomy-sessions' => __('Session'), 'menu_order' => __('Order'), 'date' => __('Date'), ); } add_action('manage_cpt_roundtable_posts_custom_column', 'manage_roundtable_custom_columns', 10, 2); function manage_roundtable_custom_columns($column, $post_id) { $the_post = get_post($id); switch ($column) { case 'menu_order' : echo $the_post->menu_order; break; } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom post types, wp admin, columns" }
How do you cite the images on your blog? I just created a blog through wordpress and there was a background that I used from < I also used two other images...so I'm just wondering, do I need to cite these images in some way? In other words...when we write an essay or something, we usually cite the sources that we use, right? How does that work for images on our website? Do I need to cite anything? I would appreciate any help, because I'm really confused....
The Frequently Asked Questions on subtlepatterns.com state: > ### How do I credit you on my site? > > You can credit using a comment in your HTML or CSS code. Example for CSS: > `/* Background pattern from subtlepatterns.com */`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, blog" }
Show custom field if it exists, and show different elements if it doesn't Basicly what I'm trying to do (with very basic knowledge of PHP): If Custom Field $randomname exists for that particular post, show the content of that custom field. If Custom Field $randomname doesn't exist for that particular post, show something else - for example: <div class="name">content</div> Any help is highly appreciated.
Inside the loop, you can check the custom field with `get_post_meta`. Like this. If custom field `randomname` exists then it will show it's value otherwise it will print `<div class="name">content</div>` <?php if ( get_post_meta( $post->ID, 'randomname', true ) ) { echo get_post_meta( $post->ID, 'randomname', true ); } else { echo '<div class="name">content</div>'; } ?> OR you can use below which is shorter version of above using Ternary Operator echo get_post_meta( $post->ID, 'randomname', true ) ? get_post_meta( $post->ID, 'randomname', true ) : '<div class="name">content</div>';
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "php, custom field" }
get adjacent post by meta key and meta value I'm trying to limit previous/next navigation to posts that have the same meta_value on a certain meta_key. I know this was asked before, but I couldn't pick a working answer. And all that I could come up with by myself is this: $keyword = get_post_meta($post->ID, 'keyword', true); $prevPost = get_previous_post(); $args = array('meta_key' => 'keyword', 'meta_value' => $keyword, 'posts_per_page' => 1, 'include' => $prevPost->ID); $prevPost = get_posts($args); foreach ($prevPost as $post) { setup_postdata($post); [...] wp_reset_postdata(); } ...but it seems to only work when two posts are next to each other chronologically as well, else it will display nothing. I suppose functions should be run in a different order, but I have no idea how to go about it.
The plugin "Ambrosite Next/Previous Post Link Plus" < ..seems to do the job well To further style the results, one could even use it like this $prev = previous_post_link_plus( array('return' => 'id') ); query_posts('p='.$prev); while (have_posts()) : the_post(); [...your stuff here...] endwhile; wp_reset_query(); $next = next_post_link_plus( array('return' => 'id') ); query_posts('p='.$next); while (have_posts()) : the_post(); [...your stuff here...] endwhile; wp_reset_query();
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "custom field, navigation" }
Output richtext metabox value I have rich text metabox.When I echo the out put it shows html tags.If I write `<h1>Hi</h1>` in editor metabox it ouput the same.My works so far <?php $valueeee2= get_post_meta($_GET['post'], 'SMTH_METANAME_VALUE' , true ) ; wp_editor( htmlspecialchars_decode($valueeee2), 'mettaabox_ID_stylee', $settings = array('textarea_name'=>'MyInputNAME',) ); ?> To display $content=get_post_meta($post->ID, 'SMTH_METANAME_VALUE', true); echo $content;
Try `echo html_entity_decode($ccontent)` .
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, metabox, wp editor" }
Log In & Log Out Code In Header I have been searching for hours. I need a code that allows me to display a Login & Register link and when logged in display the users avatar along with name and logout button. I'm not exactly great at writing php or putting them together, although I am still learning. Can anyone help me with this issue. !enter image description here !enter image description here
Try this code: if(is_user_logged_in() ) { global $current_user; get_currentuserinfo(); echo get_avatar($current_user->user_email); echo 'Hello, '. $current_user->display_name; echo '<a href="/wp-login.php?action=logout">logout</a>'; } else { echo '<a href="/wp-login.php?action=login">login</a>'; echo '<a href="/wp-login.php?action=register">register</a>'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp login form" }
Customizer: Unique identifier that distinguishes which image upload control is uploading an image In the Theme Customizer, I've got a custom `add_action('wp_handle_upload', 'upscale_responsive_bg_imgs')` which upscales responsive background images when uploaded from the theme customizer. It's working as expected but it has the unwanted effect of upscaling logo images uploaded (they should be natural size of course, not upscaled). The `$_POST` data is very simply the following, which lacks any unique identifier for the originating field. Is there any chance of useful metadata that I can key off of being stuffed somewhere else in `$GLOBALS`? ( [name] => mystiqu_template_screenshot.jpg [action] => upload-attachment [_wpnonce] => 92fec00835 [post_data] => Array ( [theme] => pure ) )
Thanks to the tipoff from @birgire in the comment, I was able to locate two things, an example of an implementation that includes `context`, here (also of note is that the Github gist has code for the very useful ability to access any image uploaded from this context previously! < /** * Example of inserting a section called "Branding" with a * context-based image uploader */ $wp_customize->add_section( 'my_branding', array( 'title' => __( 'Branding', '' ), 'priority' => 30, ) ); $wp_customize->add_setting( 'my_logo', array( 'capability' => 'edit_theme_options' ) ); $wp_customize->add_control( new My_Customize_Image_Reloaded_Control( $wp_customize, 'my_logo', array( 'label' => __( 'Logo', '' ), 'section' => 'my_branding', 'settings' => 'my_logo', 'context' => 'my-custom-logo' ) ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, customization, uploads, theme customizer" }
How to add a link to Wordpress Plugin install Listing When an user searches for a plugin from the WP Admin's Add Plugin area, I want to add a link/button to every plugin's listing area. **Which hook should I use?** The location where I want the link is marked in the screenshot below. !Screenshot Thanks in advance.
This is the filter: `"plugin_install_action_links"`. You can find this in `/wp-admin/includes/class-wp-plugin-install-list-table.php` (currently) at line 434: $action_links = apply_filters( 'plugin_install_action_links', $action_links, $plugin ); Use it like: add_filter( 'plugin_install_action_links', 'my_custom_links', 10, 2 ); function my_custom_links( $action_links, $plugin ){ $action_links[] = '<a href="">......</a>'; return $action_links; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "plugin development, hooks" }
Featured Image not displaying I upload a photo for a featured image in about page but this featured image is not displaying. What's the problem on that? My site <
See my answer here: < In addition to the `<?php the_post_thumbnail(); ?>` (where you include this is where the image will appear), you have to make sure your theme has post thumbnails support. This needs to be in your theme function file: `add_theme_support( 'post-thumbnails' );`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "images" }
Getting the IDs of a custom post type I have made a custom post 'case studies' which has a number of posts. I wish to get the IDs of each of these posts to manipulate the data, but despite looking at similar threads, I cannot piece together a way to achieve this. Something like; foreach post oftype custom, get the id I am making a function to display this information in the back end, here is the snippet below. function display_meta_box( $case_study ) { if (in_array('case_studies', get_post_types())) { ...get the IDs of all posts of type 'case_studies'... } ...do other stuff with IDs... }
Found the basis of the answer buried in the codex $args = array( 'post_type' => 'case_studies'); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); the_ID(); endwhile;
stackexchange-wordpress
{ "answer_score": 10, "question_score": 8, "tags": "custom post types" }
How to create a test that calls is_front_page in phpunit? I'm using `WP_UnitTestCase` but in my code I have this condition. `is_front_page` which I'm not sure how to simulate that in `PHPUnit` This is the piece of code that I have elseif ( is_front_page() ) { // logic } And this is how I go to a page `$this->go_to( $this->post_obj->get_permalink() ); ` How do I tell phpunit that this is the homepage?
The `is_front_page()` function calls `wp_query::is_front_page()`. If you scroll down to look at the source, you will see the code you're looking to trigger: elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) ) return true; To meet that condition, you'll just need to do this in the code to set up for the test: update_option( 'show_on_front', 'page' ); update_option( 'page_on_front', $post_id );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "php, unit tests" }
Confused about how to use wp_enqueue_style I've read the updated codex about using `wp_enqueue_style` instead of `@import`. I'm a newb and just flat out confused how to use this. My theme is athletica and my child theme is athletica-child. Do I use those name somewhere in the `wp_enqueue_style` code? I'm not sure what text in the code needs to be replaced, if any: <?php add_action( 'wp_enqueue_scripts', 'enqueue_child_theme_styles', PHP_INT_MAX); function enqueue_child_theme_styles() { wp_enqueue_style( 'athletica-style', get_template_directory_uri().'/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_uri(), array('athletica-style') ); } Also, I've seen warnings about if your parent themes use `wp_enqueue_style` in it's functions.php file. Mine does! Now what do I do?
wp_enqueue_style is a MUST to add your styles according to codex. But you don't need to use your child or parent theme name anywhere. <?php wp_enqueue_style( $handle, $src, $deps, $ver, $media ); ?> The first param $handle could be anything, doesn't matter what you put here. I can see you have used your theme name in there, it acts as an identifier so you can use anything. But, make sure they are unique in all cases. For example, if you use like: wp_enqueue_style( 'athletica-style', get_template_directory_uri().'/style.css' ); wp_enqueue_style( 'athletica-style', get_stylesheet_uri(), array('athletica-style') ); Here the handles are same, so you will see one of those css is added, not both. I think you are familiar with other parameters of this function. Note: It is not mandatory, but always a good practice to register the style using `wp_register_style` function.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "child theme, wp enqueue style" }
Add a new tab to Wordpress Plugin install Listing When an user searches for a plugin from the WP Admin's Add Plugin area, I want to add a new tab(with a link to a page) next to the current tabs. The location where I want the link is marked in the screenshot below. !Screenshot Looked for it @ < but in vain. Is it allowed by WP ? Thanks in advance.
There is the filter: **`"views_plugin-install"`** (see here). You can find it in `/wp-admin/includes/class-wp-plugin-install-list-table.php` (currently) at line 226: $views = apply_filters( "views_{$this->screen->id}", $views ); Use it like: add_filter( 'views_plugin-install', 'my_filter', 10, 1 ); function my_filter( $views ){ //Do your stuff return $views; }
stackexchange-wordpress
{ "answer_score": 8, "question_score": 9, "tags": "plugin development, hooks" }
How To Pick Custom Size Of Uploaded Image In Theme Via the_post_thumbnail();? I am designing a magazine style theme and I want different image sizes as to show on `index.php` page. Now for this, I am using `<?php the_post_thumbnail( array(100, 100) );?>` but it is picking 150x150 images not 100x100 images. So How to pick my desired different size of images that are uploaded before not after the theme using? Note: My default media setting in WordPress blog is 150x150, 300x300, 1024x1024 respectively for thumbnail, medium, large.
You can use add_image_size() function to create custom sized images. You only need to paste some piece of codes in your functions.php and then update the template files accordingly. For example : add_image_size( 'category-thumb', 300 ); // 300 pixels wide (and unlimited height) add_image_size( 'homepage-thumb', 220, 180, true ); // (cropped) And you can use below codes to load those images in your template. the_post_thumbnail( 'category-thumb' ); the_post_thumbnail( 'homepage-thumb' ); Hope this helps. See this page for more info.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, post thumbnails, media, images" }
Cannot see theme in my search I have just installed a fresh Wordpress on my own One.com webspace. I would like to install the 'Hemingway Rewritten' theme, but the search engine within my Wordpress does not appear to list this theme. Instead, a search for 'hemingway' returns an apparently older version of a similar theme, called 'Hemingway'. Why can I not see the newer version of the theme? I installed Wordpress as a fresh installation this morning, so I can't see any reason why I would have received an outdated version of the Wordpress architecture (I am on 4.0).
Themes (and plugins for that matter) in the wordpress respitory are uploaded to wordpress.org by their respective authors. These themes and plugins are not written or updated or maintainted by the Wordpress team who are responsible for Wordpress core. These plugin and theme authors are normal members of the public like you and me. It is their responsibilty to keep their plugins and themes up to date etc. What you are experiencing are most probably that the theme authour has created this version of his theme only for wordpress.com hosted sites and not for self hosted sites, and it will not be at all made available to self hosted sites. You have to remember, wordpress.com has its own respitory diffirent from wordpress.org You will need to contact the author for any further details regarding this matter
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes" }
wordpress update will overwrite files changes? I edit function.php and page.php files for my custom use, everything is fine, but i have query that if wordpress will update then it will overwrite all the files and changes made ??
Yes, theme update will overwrite its folder completely. If you are using third party theme with possibility of updates the normal practice is to put your customizations into a Child Theme for it.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "updates, core" }
MetaBox with Editor instead of textarea - html not saved I am calling several custom MetaBoxes in my custom post type on Wordpress 4 like this without using a plugin: array( 'label' => __('MyContent', myPlugin), 'id' => $prefix.'mycontent', 'type' => 'editor' ), I can see the wysiwyg editor inside the post and I can also put some text inside which also saves correctly. But when I am using HTML it's not getting saved. When I save the content and reload the page, the html has gone. What do I have to do, that html gets saved and printed in frontend? And why can't I use html in meta boxes for instance in a "textarea" - is there a reason to only get plain text? I am using meta_box.php from here: GitHub Link thank you!
I have solved this problem after many researches, just comment two lines in meta_box.php file at end. $sanitizer = isset( $field['sanitizer'] ) ? $field['sanitizer'] : 'sanitize_text_field'; to //$sanitizer = isset( $field['sanitizer'] ) ? $field['sanitizer'] : 'sanitize_text_field'; at line 692 and $new = meta_box_sanitize( $new, $sanitizer ); to //$new = meta_box_sanitize( $new, $sanitizer ); at line 697 then you can save html or css in metabos editor.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "metabox, html" }
Get post ids from WP_Query? Is there a way I can retrieve an array of post ids queried from the following: $latest = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => 3 )); if ( $latest -> have_posts() ) : while ( $latest -> have_posts() ) : $latest -> the_post(); get_template_part( 'templates/content', 'post' ); endwhile; endif; wp_reset_postdata(); * * * **Follow Up:** I used `wp_list_pluck` to retrieve an array of post ids: $post_ids = wp_list_pluck( $latest->posts, 'ID' ); Then converted the array into a string using the implode function: $post_ids_string = implode( ',', $post_ids ); Sorry for the ambiguous question.
Try $post_ids = wp_list_pluck( $latest->posts, 'ID' ); Read `wp_list_pluck`
stackexchange-wordpress
{ "answer_score": 58, "question_score": 46, "tags": "wp query, query posts" }
Don't load scripts if on mobile/tablet Would like to ask the question is it possible to stop the laoding of some scripts when viewed on a mobile/tablet device ? In the theme functions file you have `wp_enqueue_script(...)`. How would you go about loading if based on device/screen size.. Is this possible?
`wp_is_mobile()` does not really solve your problem completely. To be honest here, there is no logic in Wordpress to achieve what you want * First of all, `wp_is_mobile()` only checks for mobile devices. Tablets are excluded from this * Window sizes are determined on browser side, not server side, so there are no way for php to check window size. That is why there are also no function in Wordpress that can detect a window size The only probable way to do this is to make use of javascript. I've seen examples where javascript is used to determine window size and then do load something accordingly. I haven't tested anything like this yet, and frankly, that would also be off topic here. I would suggest that you try a few google searches and testing out a few solutions as I suggested
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp enqueue script, responsive" }
How to get post ID of the current page/post inside a widget? I'm trying hard to get the post ID of the current post/page inside a widget class but doesn't work, I know there's get_the_ID() and some other options but not a single works inside a widget. Here's my code: public function widget( $args, $instance ) { global $wp_query; $thePostID = $wp_query->post->ID; echo 'Post ID is:' . $thePostID; }
You can make use of `get_queried_object()` here, which is a wrapper for `$wp_query` and returns the whole post metadata. Here's a sample code: $queried_object = get_queried_object(); if ( $queried_object ) { $post_id = $queried_object->ID; echo $post_id; }
stackexchange-wordpress
{ "answer_score": 10, "question_score": 10, "tags": "posts, widgets" }
Is there way to redirect all blog post pages to Home page? I am creating a social bookmarking site using WordPress. I am using a custom field to store the web URL. Then when a user clicks the Title, it redirects to the original blog post page. Please check this one: < (I am creating a site like this one). I don't need blog posts because I want to save the Title, one Custom Field to save the URL, Category and Tag only. But in WordPress, there is a blank page created automatically, and even blog description is null. So when a user submits a URL, one page is automatically created. Is there way to redirect all blog post pages to Home page (only blog POST pages, not normal pages)?
Myself found the answer. I added `<?php wp_redirect( ' 301 ); exit; ?>` in single.php page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "redirect, htaccess" }
Getting thumbnail of uploaded image I want to get a 'smaller' thumbnail of a large image I have uploaded through the built in word-press media up-loader. I have briefly looked at `get_the_post_thumbnail` but I don't think that is the correct function I want because the images I want to get thumbnails are not 'featured images' > Gets the Featured Image (formerly called Post Thumbnail) as set in post's or page's edit screen and returns an HTML image element representing a Featured Image, if there is any, otherwise an empty string. I am sure I saw wp spit out a number of images when I uploaded the last one. How can I access these?
Where are you attempting to get the image? That should be the correct function: global $post; $image = get_the_post_thumbnail( $post->ID ); It will return an array of all the image sizes for that given image. You can then grab the image size out of the array, or better yet pass in a specific image size to the function to return the correct size: global $post; $image = get_the_post_thumbnail( $post->ID , 'thubmnail' ); as you can see we've passed in the 'thumbnail' image size. $image will then return the url to the image size. You can then use it in an image tag, like so: <img src="<?php echo esc_attr( esc_url( $image ) ); ?>" alt="thumbnail image">
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images" }