INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Wordpress query posts with multiple post_meta data I want to display posts in a slider that are marked as "featured". For this i created a post meta box with a checkbox. Now i have the following query SELECT wp_posts.* FROM wp_posts, wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = '' AND wp_postmeta.meta_key = 'theme_featured_post' AND wp_postmeta.meta_value = '1' AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' AND wp_posts.post_date < NOW() ORDER BY wp_posts.post_date DESC But i need another value from the post_meta table as well. So how can I select the second meta_key in the query. I could query it with > get_post_meta( $postid, 'custom_image') Cause transactions are expensive, i would like to include it in one query. The custom_image is an image id and has its own row in the table.
It's not a normal practice to use raw SQL in WP, unless you absolutely _have_ to. You should be using normal WP APIs for this and optimizing _after_ you encounter a performance issue. Among other things APIs will transparently _cache_ data (such as post meta) within page load and between page loads with Object Cache installed. In typical cases Object Cache will be _faster_ than database fetch (which is the point of it).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, query, post meta, wpdb" }
How to set a default value in a meta box I found a post for adding units of measure after a price in woocomerce sites. It works wonderfully for me. Adding unit amount after WooCommerce price. I want to add a default value since 95% of my products are all sq ft. Im hoping this will make it so all products show sq ft, but the few products I change to new values will have the new value displayed. **Edit** Here is what I ended up using to accomplish this. //add default of sq sf add_filter('woocommerce_get_price_html','wpse103469_add_price_per_unit_meta_default'); function wpse103469_add_price_per_unit_meta_default( $price ) { $default_units = __( 'sq. ft.', 'myplugin_textdomain' ); $units = get_post_meta( get_the_ID(), 'wc_price_per_unit_key', true ); return ( $units ) ? $price .= ' ' . $units : $price .= ' ' . $default_units; }
Here's a tweaked version of the referenced `wpse103469_add_price_per_unit_meta_to_price()` function. If no units have been specified, the default units are appended to the price, otherwise the user-specified units are used. add_filter('woocommerce_get_price_html', 'wpse103469_add_price_per_unit_meta_to_price'); function wpse103469_add_price_per_unit_meta_to_price( $price ) { $default_units = __( 'sq. ft.', 'myplugin_textdomain' ); $units = get_post_meta( get_the_ID(), 'wc_price_per_unit_key', true ); return ( $units ) ? $price .= ' ' . $units : $price .= ' ' . $default_units; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic" }
Remove all removed pages from wordpress I am creating a plugin in wordpress and the thing I am trying to do is to create pages with code using `wp_insert_post`. After creating each page and removing all of them the new page with the same slug is being created with this format `slug-number`. My question is how can I remove the page entirely from wordpress and database so each time a page is being created the previous one be deleted completely and the new ones slug become just the slug I provide without any number attached at the end of slug?
You must use `wp_delete_post()` with second parameter set to `true`. The post will be completely deleted, not trashed. // Use $args to get the pages you created previously // See $pages = get_pages( $args ); if( $pages ) { foreach( $pages as $page ) { wp_delete_post( $page->ID, true ); } } After that, you can use `wp_insert_post()` to create a new post with a slug previously used. It may worth to consider to update the post instead of delete and create a new one.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, wp insert post" }
Do one have to wait after pressing "update" on a post edit page? Do one have to wait after pressing "update" on a post edit page (becuase if he won't the post update process will be ruin) or does it make no difference what happens after one clicked the button?
If you don't need to see the results, you don't have to wait (OTOH if you don't wait you will not be sure if it was actually sent, or maybe you had a wifi problem preventing it, unlikely event but does happen from time to time.)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, post editor" }
Choose default template for a page with code I am creating a page using the `wp_insert_code` the page is being created just find. I want to choose a default template for the page I am creating which the template is inside plugin folder in a templates folder. I tried to use this code: update_post_meta($post_id, '_wp_page_template', $page_template_path); It does work when ever a template in defined inside the theme directory but I want to have templates files inside plugin folder. To make my plugin reusable and easy to setup. Can you help me figure that out?
Here is your answer. Go to this GitHub repository and follow the instructions.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, pages, wp insert post" }
How to use rewrite rule or rewrite endpoint to switch languages? The goal is to have this working: www.pageurl.de -> nothing happens www.pageurl.de/en/ -> a variable is set and stored in a cookie this also need to work with permalinks, categories etc. like this: www.pageurl.de/en/linktopost/ www.pageurl.de/en/categoryname/ i tried to work with `add_rewrite_endpoint('en',EP_PERMALINK|EP_PAGES|EP_ROOT|EP_CATEGORIES);` but the endpoint (that makes sense) only works at the end of the url i also tried to work with `$language="en"; add_rewrite_rule('^' . $language . '/([^/]*)/?$', 'index.php?lang=$matches[1]', 'top'); ` but www.pageurl.de/en/ only returns a 404 What is the best way to do this? I need to have the language pattern in the url on the whole page, lets say after changing the page in a menu the "en" has to be in the url.
You cannot do this by just adding a rewrite rule, you need to change every recorded rules. Here is a simple way to do this: function my_rewrite_rules($rules) { $new_rules = array(); $new_rules['(?:de|en)/?$'] = 'index.php'; foreach ($rules as $key => $val) { $key = '(?:de|en)/?' . $key; $new_rules[$key] = $val; } return $new_rules; } add_filter('rewrite_rules_array', 'my_rewrite_rules', 11); Now you still need a way to receipt the language value in order to save it in a cookie. You could add a parameter for the language, in order to get it inside the `$_GET` super global. But that would means to offset all other parameters of all other rules, and this would involve a lot of regex. Instead you can simply get the language by querying the `$_SERVER` global: preg_match('/\/(de|en)(\/|$|\?|#)/', $_SERVER['REQUEST_URI'], $matches);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "rewrite rules, multi language" }
Separate Custom Post Type Taxonomy by Comma I tried to figure out how to separate the custom post type taxonomies. $terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) ); foreach ( $terms as $term ) { $term_link = get_term_link( $term, array( 'commitments', 'type' ) ); if( is_wp_error( $term_link ) ) continue; echo '<a href="' . $term_link . '">' . $term->name . '</a>'; } Each taxonomies show correctly. However, I cannot separate them in comma. it shows "TaxonomyATaxonomyB" but I want to show it as "TaxonomyA, TaxonomyB" How to do it? or is there any other way around? Thanks!
You can use a counter to determine if you need to add a comma or not : $terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) ); // init counter $i = 1; foreach ( $terms as $term ) { $term_link = get_term_link( $term, array( 'commitments', 'type' ) ); if( is_wp_error( $term_link ) ) continue; echo '<a href="' . $term_link . '">' . $term->name . '</a>'; // Add comma (except after the last theme) echo ($i < count($terms))? ", " : ""; // Increment counter $i++; }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "custom post types, custom taxonomy, terms" }
Use WordPress function in php file I have a WordPress Child Theme and I have added a php file to this child theme. Also I want to use WordPress functions in this file ( I want to show header, menu and footer ) So I try <?php $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] ); require_once( $parse_uri[0] . 'wp-load.php' ); ?> Also I try to add header and footer <?php get_header();?> //my content <?php get_footer(); But it seems it can't load all css/js files and page have bad styling.
There are two things to do to make this work. First, you have to turn your php file into a template that can be recognized by WordPress. This is simply done by adding the following to the top of your file: <?php /* Template Name: WPSE Example Template */ ?> The second thing is, you must make sure this file is not called directly, but through WordPress, so functions like `get_header` are recognized. This you do by making a page in WP. You can leave everything blank, including the title. Just make sure that you assign your template as the one to be used by this page. Use the permalink generated when you save the page to display it.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, functions, theme development, pages, templates" }
Localhost port is missing on some links after downgrading MAMP I downgraded to MAMP after trying MAMP pro, everything is fine except some of the links don’t have localhost port; eg…localhost/about, when it should be localhost:8888/about. Some of the links include the port, and some don’t, but I’m not sure why? Any ideas would be greatly appreciated. Thanks!
If some of your link are using `localhost` while others are using `localhost:8888`, you'll want to make sure that all of the links in your database are set to `localhost:8888`. Follow these steps: 1. Go and download Interconnect IT's Database Search & Replace Script here 2. Unzip the file and drop the folder in your **localhost** where your WordPress is installed (the root) and rename the folder to **`replace`** (screenshot) 3. Navigate to the new folder you created in your browser (ex: ` and you will see the search/replace tool 4. Enter your `/localhost/` URL in the **`search for…`** field and the new URL (`/localhost:8888/`) in the **`replace with…`** field You can click the _dry run_ button under _actions_ to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "urls, localhost" }
Creating Custom Hook for my plugin In my plugin I have in admin menu function Media Organizations List. Here I get a list of all Organizations. There are 3 organizations types * affiliate * direct * bureau The total list will get long. Therefor I need a custom hook to filter the 3 organization types to get a better view. I have read several documents but not understand exact what to do. Is there someone of you who can help me making this custom hook? It would be very helpful.
First, register the filter hooks with the handy `apply_filters` tool: function wpse_238394_org_types() { return apply_filters( "my_org_types", array( "affiliate", "direct", "bureau" ) ); } Now, `wpse_238394_org_types()` will return the default 3 types being not filtered yet, so we one more custom type: add_filter("my_org_types", function($types) { $types[] = "custom_type"; return $types; }); Now if you debug `wpse_238394_org_types()` it should be including the `custom_type` item along the defaults. Hope that helps. Please also take a look at the docs < as jdm2112 suggested.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, hooks" }
Changing WordPress routing to load the same page for different URLs I'm converting an existing website to a WordPress theme. One of the pages is a gallery that uses JS `history.pushState` to create unique URLs for loading certain images. E.g. page URL (non WP website): ` URL for a certain image: ` I would like to preserve this functionality in WordPress. However, when loading the URL for a certain image, WordPress considers it as a different page and displays a 404 error. Is there a way to configure WordPress or `.htaccess` so that when such image URLs are loaded it will keep the URL and load the gallery page, thus displaying the relevant image in the gallery page?
I ended up using add_rewrite_rule: function bones_rewrite_rules() { $gallery_page_id = 395; add_rewrite_rule('^gallery/img-.*', 'index.php?page_id=' . $gallery_page_id, 'top'); } add_action('init', 'bones_rewrite_rules');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks, htaccess, routing" }
How to use command lines an activate theme in wp - cli also setup Vagrant/Sage Theme? I'm still a beginner using Command lines and Sage Wordpress Starter Theme Write steps on what I did to setup everything on my iMac . If you need how wp-cli works and Sage Wordpress Starter works please help me. First Step: I have setup my VVV server and did the vagrant ssh. After I did vagrant ssh I create a new theme based on Sage by using Composer (composer create-project roots/sage web/app/themes/your-theme-name 9.0.0-alpha.1). Second Step: I got confuse on try to understand how to add a new theme inside my Wordpress-Develop folder and they make it activate by using wp-cli. Three Step: Install dependencies I can do myself just need help with this second step. $ wp theme activate your-theme-name
* A theme slug, the path to a local zip file, or URL to a remote zip file. * If set, get that particular version from wordpress.org, instead of the stable version. * If set, the command will overwrite any installed version of the theme, without prompting for confirmation. * If set, the theme will be activated immediately after install. # Install the latest version from wordpress.org and activate $ wp theme install twentysixteen --activate Installing Twenty Sixteen (1.2) Downloading install package from Unpacking the package... Installing the theme... Theme installed successfully. Activating 'twentysixteen'... Success: Switched to 'Twenty Sixteen' theme. # Install from a local zip file $ wp theme install ../my-theme.zip # Install from a remote zip file $ wp theme install
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "themes, wp cli" }
How to show select_advanced content instead of ID? When I am using this code, it only shows the ID instead of its content. I want to show the content instead, how can fix this? array( 'name' => __( 'Select Home Team ', 'themepixels' ), 'id' => "{$prefix}select_home_team", 'type' => 'post', 'post_type' => 'football_team' , 'options' => array( 'type' => 'select_advanced', 'args' => array() ), 'multiple' => false, ), ..... <div class="home-team"> <?php $home_team_name = rwmb_meta( 'pb_select_home_team', 'type=select_advanced', get_the_ID() ); ?> <?php echo esc_html( $home_team_name ); ?> </div>
This is the answer: echo get_the_title($home_team_name)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "metabox" }
How can I get the intended URL in a 404? I am customizing a `404` page, and I would like to know the correct way to get the intended URL within `404.php`. Do I use `$_SERVER['REQUEST_URI']` as some online resources seem to suggest, or is there a WordPress builtin?
`$_SERVER['REQUEST_URI']` is your only option. wordpress failed parsing the url so not much you can get from the API
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "customization, urls, 404 error" }
How to detect the context of homepage for a wordpress mu sub-blog I'd like to do this when clicking on home icon : * if we are not on the homepage of a sub-blog, go to the homepage of the sub-blog * if we are on the homepage of a sub-blog, go to the homepage of the whole site I'm beginner and don't know how to detect the context of homepage for a wordpress mu sub-blog, any idea, thanks ?
You could test using the following conditionals //if you aren't on the main site, and aren't on the homepage if (!is_main_site() && (!is_front_page() && !is_home())) { print "<a href='sub-blog-homepage'>home</a>"; } //if you aren't on the main site, and aren on the homepage if (!is_main_site() && (is_front_page() && is_home())) { print "<a href='main-site-homepage'>home</a>"; } Also depending on how your sub-blog homepage is configured, you could use either `is_front_page()`, `is_home()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite" }
Menu position (admin menu) of pages Is there a method to change the menu position of the 'pages' post type? When registering new custom post types, you can enter an integer in `menu_position` but how do I do this for the preregistered post types? Can I somehow overwrite this? PS: I need it to be 5.
you cannot put this on position `5` because there is something but you can put it on `4.5` with this code : add_action("admin_menu", function () { $GLOBALS["menu"][4.5] = $GLOBALS["menu"][20]; unset($GLOBALS["menu"][20]); });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "custom post types, pages, admin menu, menu order" }
How to write "alt" tag in image for wordpress code? I want to use the code `<img class="img-responsive" src="<?php echo the_post_thumbnail_url(); ?>" alt="" />` instead of `<?php the_post_thumbnail(); ?>`, to output the post thumbnail. Now, how can I get "alt" and "title" dynamically for post thumbnail. Is there any function provided by wordpress for this. I looked for a function from wordpress codex/developer site for this problem but I didn't find one.
Why would you want to avoid `the_postthumbnail`? It can give you the exact html you want if you use the right attributes. Anyway, you can access the title and alt tags of an image like this: // get the ID of the featured image $thumbnail_id = get_post_thumbnail_id( $post_id ); // retrieve title (an image is a post, so you can access the title as if it is a post title) $title = get_post($thumbnail_id())->post_title; // retrieve alt (which is stored as metadata to a post) $alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, plugin development, theme development, images, themes" }
How can I get $pagenow equals to the Home Page or specific page on my site? I'm new to WP and search for some examples on `$pagenow` codes. Everything I saw equals to .php files. How can I make an if statement that `$pagenow` is equal to my Home Page or specific page?
The `$pagenow` variable is specificly meant to identify pages in the admin area. It cannot be used on the frontend of the site. There is another set of tests to identify pages on the frontend. `is_home`, for instance, tests whether the current page is the homepage, while `is_page('about-us')` will test whether you are on the About Us page. There is an overview of these tags.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "conditional tags, homepage" }
How to show post title outside of loop? I am using following codes to show title of a post in another post.But it shows only post id.How to solve this? <?php $home_team_name = rwmb_meta( 'pb_select_home_team', 'type=select_advanced', get_the_ID() ); ?> <?php echo esc_html( $home_team_name ); ?> Thanks
Because you're outside the loop, you'll need to either know the post id of the title you want and specify it in the function parameter, or call the global $post variable if you're on the page (just not in the loop yet). global $post echo get_the_title($post->ID); or echo get_the_title(2);
stackexchange-wordpress
{ "answer_score": 9, "question_score": 2, "tags": "custom post types, posts" }
Move some files of plugin to the root directory with plugin activation I want to move some plugins files to the root directory of the website after plugin activation. Is it possible?
There is no safe way to do that, and even if you succeed, you will cause a lot of trouble for your users. * The root directory for the web site is `$_SERVER['DOCUMENT_ROOT']`. You might not have write access here, because that can, and maybe should, be turned off. * WordPress might be installed in a subdirectory; now it's unclear what the "root" is from your point of view. * There might be other files with the same name already in that place, because your plugin might be active in some sites of a multisite, or one WP installation is used for multiple, separate sites. If you need an address on the root level, use one of the better options: * register an endpoint * use a page template * hook into `template_redirect` to deliver your custom code
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugin development" }
How can I display a list of pages and the template used by each? I want to display a list of pages and the template used by each. The code I’m currently using is below, but the result is a bit verbose. <?php global $wpdb; $sql = "SELECT post_title, meta_value FROM $wpdb->posts a JOIN $wpdb->postmeta b ON a.ID = b.post_id WHERE a.post_type = 'page' AND a.post_status = 'publish' AND b.meta_key = '_wp_page_template' "; $pages = $wpdb->get_results($sql); echo '<pre>'; print_r($pages); echo '</pre>'; ?> The output is… [1] => stdClass Object ( [post_title] => Notes [meta_value] => default ) I want to simplify it to something like… [1] Notes => default
You could try this quick piece of code, it doesnt output to array though. $args = array( 'meta_key' => '_wp_page_template', 'sort_column' => 'post_title', 'sort_order' => 'desc'); $templates = get_pages($args); foreach ( $templates as $template){ $templatePage = $template->meta_value; $templateName = $template->post_name; echo "Named Template: {$templateName} - - {$templatePage}\n"; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates" }
Admin menu structure Currently I'm working on a website and I want to separate the header- posts from the rest of the posts in de admin post menu. I added a menu-item which filters the category "header". But I want to exclude the header category from the post-list in the posts-menu. <?php add_action('admin_menu', 'events_menu'); function events_menu() { add_menu_page( 'Header', 'Header', 'manage_options', 'edit.php?category_name=header', '', '', 4 ); } ?> The above code gives me a header menu-item with all the the category header posts. But I can't seem to figure out how to exclude the category header from the post-menu section. Thanks!
Reposting as an answer since that solution worked for you. Please accept it as your answer. * * * Now that I think of it, why don't you just make your header posts a custom post type? It seem like that would give header posts their own space and keep them out of the standard posts menu. It might be easier to use on the front end as well
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "menus, admin" }
Multisite install - Create each domain with its own directory I am rather new to WordPress and trying to install a multisite install where I have my main WP install in \var\www\html and each new site/domain I create would be created in its own folder. So what I am looking for is: * site1.com - main site in \var\www\html\ * site2.com - site in \var\www\html\site2.com\ * site3.com - site in \var\www\html\site3.com\ I'm thinking this should this be a directory install but I may haveto do something with .htacccess or httpd.conf in order for things to work how I'd like? The WP multisite install (4.6.1) is on AWS running Ubuntu 14.04. I included the httpd.conf file from Apache config.
The setup you want will give you three isolated installations. The benefit of using WordPress Multisite is that from one login you can access all three sites, also it allows you to do upgrades and control the plug-ins and themes for all the sites. Basically it's like having your own wordpress.com. Now depending if it is a new install or not it will define your structure. Please refer to the WordPress Codex for more details: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, installation" }
Add a new data attribute in <img> tag I would like to use Qazy Lazy load and I need to include new data attribute `data-qazy="true"` inside all `img` tags. I tried to include with this function, but it only applies for sidebar images and doesn't work for the post images: function add_lazyload_atts( $atts, $attachment ) { if ( ! wp_get_attachment_image_src( $attachment ) ) { $atts['data-qazy'] = 'true'; } return $atts; } add_filter( 'wp_get_attachment_image_attributes', 'add_lazyload_atts', 10, 2 );
I found the solution to add that attribute to the `img` tag with this function: add_filter('the_content','new_content'); function new_content($content) { $content = str_replace('<img','<img data-qazy="true"', $content); return $content; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "images, attachments" }
Display post in visual composer with custom html Im learning the way to display post with custom html style. Because Im using VC so I wonder if there are any element that would display post by category or tag, then we can go to the function and custom its html and style? I was working with a theme and it has something call "Popular post" and they actually can replace its shorcode to do some custom ("ww-shortcode-blog-popular") after searching for day I can't find a single document about it so it must be something specific for that theme then. Im so new please help me.
You can create your own custom shortcode and then map it with vc_map(). You can read about it here: < . You can also modify already existing visual composer shortcodes < , but I didn't tried that yet.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts" }
Incrementing content with extra text after save/publish I'm using one plugin for slicing post to various subposts. And now I want to add to the end of the content one line of the text with page break tag and shortcode on post publish. But the code I wrote isn't working: add_filter('publish_post', 'increment_content'); function increment_content($content) { $content .= '<!--nextpage--> [display-posts category_display=\"true\" image_size=\"thumbnail\" title=\"Suggested Posts\" wrapper=\"div\" wrapper_class=\"suggested\"]'; return $content; } What am I doing wrong?
Try using `add_filter('the_content', 'increment_content', 20);` Your current function should be added as you assume.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, hooks" }
How to link file or image from wordpress plugin dir to theme by using themes function.php, is it possible? I have some image file in my plugin directory. I want to display those file by using my theme function. I am trying many way but something was wrong. Theme and plugin both dir is loaded at same time. Can you help me? $link = plugins_url( 'img/btn-arrow-left.png',__FILE__ ); //$link = plugin_dir_url( 'img/btn-arrow-left.png',__FILE__ ); $aro_left = '<img src="'.$link.'img/btn-arrow-left.png"/>'; var_dump($link); Output : string ' (length=113)
You are almost there. Try `plugins_url('plugin_dir_name/img/name of.png').`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, themes, urls, bug" }
postsperpage value not being applied I have a custom post type called `laptop`, and in my theme's `front-page.php` I have: $loop = new WP_Query( array( 'post_type' => 'laptop', 'postsperpage' => '30' ) ); if ( $loop->have_posts() ) { ?> <!-- display laptops --> However, only 10 laptops are displayed. I find that in `Settings > Reading > Blog pages show at most` was set to `10`, and changing this number changes the number of laptops displayed on the front page. Am I wrong in thinking `postsperpage` should override `Settings > Reading > Blog pages show at most`?
Because it's not `postsperpage` but `posts_per_page`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, wp query, loop, query posts" }
wp_update_post using post_name Can I update posts using the `post_name` (slug) instead of the `ID`, as I don't have a list of the ID's, but I do have the list of the slugs and the corresponding changes for each one?
$post = get_page_by_path( 'the_slug', OBJECT, 'post_type' ) ; $id = $post->ID; Then you an update post using this ID. Note: Untested, may contain syntax error.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp update post" }
How Add a Save Button to Custom Meta Box without Leave/Stay js Dialog? I remove the publish default button and add a custom submit button for the post page, but wordpress save it like a draft after showing the (js alert) dialog: "stay or leave the page?"
HERE THE SOLUTION: If you want remove the default publish button and use a custom submit button for your Custom Meta Box, you have to insert the submit_button in a `<div class="submitbox" id="submitpost"></div>` e.g. <div class="submitbox" id="submitpost"> <?php submit_button( 'Submit', 'primary', 'publish', false ); ?> </div>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "metabox" }
How to add post classes? I can use `post_class()` to echo all classes for a post. How can I output only the `category-ID` as a class, and how can I include this while using `heredoc string syntax`? I got this function in which I would like to use `post_class()`, and I have tried `get_post_class()` which does not work, because its an array to string conversion. function imageHolder($ID) { $classes = get_post_class($ID, 'image-holder'); return <<<HTML <div $classes></div> HTML; } echo imageHolder(2);
function imageHolder($id){ $category = get_the_category($id); $class = '"category-' . strtolower($category[0]->cat_name) . '"'; print <<<HTML <div class=$class> This is a Test </div> HTML; } imageHolder('1'); Please be careful about using '/n' or '/r' symbol in the Heredoc syntax(they might cause the function does not work properly).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, post class" }
add_filter OO with parameters How to use Oriented Object concept in `add_filter` or `add_action` with priority and number of parameters? This is possible without additional parameters: add_filter('wp_get_attachment_image_src', array($this, 'useCDN'); With parameters this is possible? How to?
It's done the same way you would do in procedural, you need to provide the `priority` and the `number of parameters` so you would have; add_filter('wp_get_attachment_image_src', array($this, 'useCDN'), 10, 3); to pass 3 additional parameters to the filter
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "plugin development, filters, actions" }
How to force stylesheet to load before anything else in header? I need a stylesheet to be added to the header before anything else. That means before any styles or scripts that are automatically added by any of the plugins I'm also using. I figured I could add this stylesheet with wp_enqueue_script, but I'm not sure how to force it to be loaded before other stylesheets or scripts that I do not have control over. Thanks. *This is for a theme which I need to add a stylesheet to. This is not for a plugin I'm building.
The tag that you want to call to execute your function is the `wp_head()` with a priority of `1`. In your child theme's `functions.php` file, add the following: add_action( 'wp_head', 'wpse_239006_style', 1 ); function wpse_239006_style() { wp_enqueue_script(); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "wp enqueue style, css" }
Where is the correct place(s) in twentysixteen's header.php to add a Google webfont? I have a slightly tweaked child theme to twentysixteen (used solely on ` \- feel free to view source!), and I would like to add a Google webfont. < suggests (as one option) to put e.g. `<link href=" rel="stylesheet">` before your theme imports its stylesheet. That sounds like sensible enough advice, but twentysixteen's `header.php` does not contain strings I could find like "css". As a result, I don't know where the last line is in `header.php` before the theme's stylesheet is loaded, or whether (in a child theme to twentysixteen) I should be editing some other file (and if so, which?). I have provisionally placed `<link href=" rel="stylesheet" />` in `header.php` just after the open HEAD tag, but I suspect there are better or more surgical placements. Where, in a twentysixteen child, should I place an HTML tag to import a Google font or the like? Thanks,
You can place it in `header.php` between starting `<head>` and closing `</head>` tags and it should work properly. Or perhaps a better solution would be to enqueue the style in functions.php function google_fonts() { $query_args = array( 'family' => 'Sigmar+One' ); wp_register_style( 'google_fonts', add_query_arg( $query_args, "//fonts.googleapis.com/css" ), array(), null ); } add_action('wp_enqueue_scripts', 'google_fonts');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "theme development, templates, child theme" }
My WP site and password was hacked, what to do? Today I realized that my WordPress blog was hacked. I noticed, because the title was altered to something like: +ADw-/title+AD4-Hacked By *** +ADw-meta http-equiv+AD0AIg-refresh+ACI content+AD0AIg-5+ADs-URL+AD0- +ADw-DIV style+AD0AIg-DISPLAY: none+ACIAPgA8-xmp+AD4- After a while I couldn't login with my usual password, so I went to the host's cPanel and I tried to reset my WordPress password in the `wp_users` database, with the help of phpMyAdmin. There, I can see that somebody altered the login information to " _indoxploit_ " and maybe the password MD5 hash was also altered, because when I searched it in google I got this page hit: Then I simply added a new MD5 hash and then I was able to login to my WP admin dashboard, I updated the WordPress version to the newest one, and the plugins too. What to do besides these actions?
Nice job recovering your password, however, the exploit probably still exists so you might get hacked again. Your next step is to find and seal up the security hole. It could be a plugin. It could be a theme. Download and run the Sucuri plugin to help you figure it out.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, htaccess, security, password, hacked" }
How can I include private pages in a page list? I'm currently using wp_list_pages to show site pages. It doesn't include private pages, so I need to find a way to produce a list of them too. I can do it with a plugin, but it includes various options I don't need and I prefer to hardcode something appropriate into a template.
You can just add a `post_status` argument: wp_list_pages( array( 'post_status' => array( 'publish', 'private' ), ));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp list pages" }
Difference between widget form code variables I'm attempting to create my first ever widget and was hoping someone could explain the difference between `$this` and `$instance` used in the following widget form code. <?php public function form($instance){ ?> <label for="<?php echo $this->get_field_id('title'); ?>">Title: <input type="text" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo $instance['title']; ?>" id="<?php echo $this->get_field_id('title'); ?>" /> </label> <?php }
`$this` is the widget object, an instance of the relevant widget class. It includes things like the widget ID and class identifiers which are required for the method that generate the input id and name attribute in the snippet `$instance` is the array which includes the widget setting. The settings ae not stored as part of the object and therefor needs to be passed as a parameter
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "widgets" }
Secondary navigation menu on one page I have this wp designed link where i have Home, Services, About, and Contact. Under Services i have separate menus like webdesign, webdevelopment, seo, maintenance and so on.. I have created the secondary nagivations in the menu page (Admin > Appearance > Menu). I have this code. <?php wp_nav_menu( array( 'theme_location' => 'secondary-menu', 'menu_class' => 'secondary', 'fallback_cb' => '' )); ?> Where should I place this, because the `pages.php` is for all the pages.
If you need this menu on one page only, let's say About Us (slug: `about-us`), you can easily add a conditional like this in `pages.php` at the place where you want the menu to appear: if (is_page('about-us')) { wp_nav_menu( array( 'theme_location' => 'secondary-menu', 'menu_class' => 'secondary', 'fallback_cb' => '' )); } Remember that if you have a third party theme, you should build a child theme for this page, because else your adaptation will be lost when the theme is updated.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, menus, templates" }
Error 404 when saving or previewing one specific page While the whole site seems working correctly, I have one specific published page that will throw a 404 error when previewing or saving. WP 4.6.1 installed: Attempts made till now to fix: * saved permalinks (currently set to Day and name) * disabled all plugins * deleted cookies from browser * checked out WordPress Address (URL) & Site Address (URL) consistency * reverted to draft (cannot save however gives 404) * created a new page and imported content Could it be possible that some server settings are preventing page save/preview on some pages
The problem was due to a security setting in the server (Apache). Changed a rule and voilà!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "404 error, save post, previews" }
Advanced ordering of query_posts I'm working on a rather large and old Wordpress project where someone has previously used `query_posts` all over the place. For this reason, I'm unwilling to change those method calls. I'm not the maintainer of the site, I'm doing a quick fix. Each post in question has a field called `our_date`, which represents a date and a time, and `title`. The customer wants the posts ordered by `title`, but so that the _future_ posts appear first in the list and all the past dates at the bottom. This is what I'm working with right now: 'orderby' => array('date' => 'ASC'), What's the best way to accomplish this custom sorting of results from `query_posts`?
I don't think this is doable in a single WP API query. You just don't sort whole set with single logic, you have logic _changing_ halfway. I don't think even SQL can express this. It is hard to advise without seeing specific circumstances (such as counts, pagination involved and so on), but my first thought would be to split this into two queries: 1. "Future" posts (meta query for date field in future, order by title) 2. "Past" posts (meta query for date field in the past, order by title)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp query, order" }
Why isn't this youtube shortcode working? echo do_shortcode(' Is merely printing out onto the page. I know I can display the video with html with <iframe src=" width="560" height="315" frameborder="0" allowfullscreen></iframe> but I'm trying to leverage wordpress' built-in methods. How do I do this?
I think this is what you are looking for: <?php echo wp_oembed_get(' ?> For more details check this documentation.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "shortcode, youtube" }
Site Cookie Error, Redirection and Blank Pages after Upgrade I've updated my site < to the newest version of WP. The theme and all the plugins are updated but I get the following errors: * Cookie error when login. * When I save, for example, Writting options in WP Dashboard it redirects to a blank page. * The velo-classique.com don't redirect to www.velo-classique.com. I've checked the database, the wp-config.php and many thing that I've read on the Internet and troubleshooting section of WordPress and nothing works. What can it be?
There are newlines being generated before your `<!DOCTYPE>` declaration, which you can see by viewing the source code of your site from your browser: ![enter image description here]( As Rarst suggested, there is probably some incompatible code that is causing this output to be generated. The extra whitespace can cause the issues you've described. There are many resources on this site and others about troubleshooting whitespace appearing before the doctype declaration.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "updates" }
get posts by tag to showing in a widget Hi there dear developers! i make a widget in my wordpress theme to show 5 last video-based posts in that. and my video posts have a 'video' tag. how i can query that posts by tag to showing there? thanks.
You might want to go through: < So using `tag` parameter in `WP_Query`, you can get posts tagged to 'video' tag. Use `orderby` and `posts_per_page` to get last 5 video posts. $query = new WP_Query( array( 'tag' => 'video', 'posts_per_page' => 5 ) ); while ($wp_query->have_posts()) : $wp_query->the_post(); //your code to display posts endwhile; Haven't tested the code, so watch out for typos.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query, tags, get post" }
How to add custom CSS and JavaScript file for wp- admin dashboard (backend) I want to add some CSS and JavaScript to the WordPress dashboard but only for my custom post type design and some script functionality. Can any one suggest to me about how to include my custom CSS and JavaScript files for backend users?
You have use `admin_enqueue_scripts` hook to include css and js in your backend. So instead of: add_action('wp_enqueue_scripts', 'your_function_name'); Use: add_action('admin_enqueue_scripts', 'your_function_name_for_admin');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin" }
How to customize pagination links? The default setup for `paginate_links` is very odd to me. For example if I'm on page 5 of a total of 9 pages, this is how it will display: <prev 1 ... 3 4 [5] 6 7 ... 9 next> What I want to achieve is to display it something like Google search results page where I only show the current 5 (Google does 10) pages. I don't see any dots and I don't see the last page or the first pages unless I'm within that 5 page range. I want the user to click next as many times as needed to reach the end. So in other words the user doesn't know the total number of pages. Something like this: On the first page: [1] 2 3 4 5 next > One the fifth page: <prev 3 4 [5] 6 7 next> Is this possible?
I'm not going to copy and paste someone else's code and explain how to.. just a 5 minute search on google "customize pagination WordPress demo" result: Great tutorial of how to set pagination I think this is exactly what your looking for.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "pagination" }
How to add a column to the Trash page? I'm trying to add a column to the trash page for posts and pages but can't find a way to hook into that specific area. I've been able to use functions like `manage_posts_columns` and `manage_pages_columns` to add columns, but these hooks add columns to more than just the trash view. I can see from the URL that the trash has `post_status=trash` but haven't found a way to hook into that. The generic `manage_{$post_type}_posts_columns` doesn't seem to fit since I need a post_status, not a post_type. I've also looked at `get_current_screen` but it doesn't return a post_status. Am I missing a function or obvious way to do this?
You can check the value of the `post_status` query variable and make sure that it's set to `trash`: function wpse239286_trash_column( $columns ) { // Bail if we're not looking at trash. $status = get_query_var( 'post_status' ); if ( 'trash' !== $status ) { return $columns; } return array_merge( $columns, array( 'trash_column' => __( 'Trash Column', 'text-domain' ) ) ); } add_filter( 'manage_posts_columns' , 'wpse239286_trash_column' ); add_filter( 'manage_pages_columns' , 'wpse239286_trash_column' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "functions, wp admin, admin, columns, trash" }
how to get my WP site's IP? Built new web site on WordPress. Added its domain to Network Solutions. Need to know IP address of WordPress site to set the A RECORD on Network Solutions, which hosts the domain. On WordPress.com cannot figure out how to look up the IP of my site there. (And their chat is down for week.)
This is more a general hosting question, rather than WordPress. Nonetheless, since you mentioned that you have your website on WordPress.com, you can have your new domain point to your WordPress site by it's CNAME. In your case, your CNAME would look be `example.wordpress.com` (change `example` to your actual site). This is the recommended approach since using a CNAME rather than the A record because if WordPress.com changes your IP, the CNAME will alway point to the right one. Otherwise, check out this article that WordPress provides to point your custom domain: Use a Domain You Already Own (Domain Mapping)
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "redirect, domain, domain mapping, dns" }
Searching for themes that post full article on home page by default I understand there is way to change `the_excerpt` to `the_content`. But do any of the existing "features" on the search feature (under add new themes) indicates the `the_content` is already the default option for the theme?
No. The search function essentially captures the header of the theme's `style.css` file, which contains two types of information that relate to the theme's properties. There is a description, which holds a free text and there are some tags which must be chosen from a fixed list. The excerpt/content choice is not among the tags. The free text may contain some information, but it is not systematic data.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, the content, excerpt" }
Replace a part of url generated by get_term_link Is there a way to edit a text in url given by get_term_link() I want to replace this text `listing-category/` in all the links generated by get_term_link() Till now I have been using the following code to do it manually wherever i wanted but now I realize that it will be efficient . $term_link= str_replace('listing-category/', 'jobs/?fwp_cate=', get_term_link( $term )); $term_link= rtrim($term_link, '/'); So is there a way to apply the above code in all the get_term_link() Please help me out on this
Yes, there is a hook "term_link" which you can use for this purpose. Here you can find documentation. < so the solution will be like this add_filter('term_link', 'term_link_filter', 10, 3); function term_link_filter( $url, $term, $taxonomy ) { $url= str_replace('listing-category/', 'jobs/?fwp_cate=', $url); $url= rtrim($url, '/'); return $url . "#results"; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "filters" }
the_post() is printing titles in page footer I'm making a really simple cycle where I need to print a Custom Post Type with my style (that isn't defined yet in the script below but is where I print the_thime) and it's working. The problem is that in the bottom of the page, just before the footer, "something" is printing the title of my posts. That's the function: function shortcode_eventi() { query_posts(array( 'post_type' => 'eventi' ) ); ?> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <small><?php the_time('F jS, Y') ?></small> <?php endwhile; ?> <?php else : ?> <h2 class="center">Not Found</h2> <p class="center"><?php _e("Sorry, but you are looking for something that isn't here."); ?></p> <?php endif; ?> <?php } No ideas about the problem.
Instead of `query_posts()`, use `WP_Query()`: function shortcode_eventi() { $loop = new WP_Query(array( 'post_type' => 'eventi' )); ?> <?php if ($loop->have_posts()) : ?> <?php while ($loop->have_posts()) : $loop->the_post(); ?> <small><?php the_time('F jS, Y') ?></small> <?php endwhile; ?> <?php else : ?> <h2 class="center">Not Found</h2> <p class="center"><?php _e("Sorry, but you are looking for something that isn't here."); ?></p> <?php endif; ?> <?php } Read about WP_Query on the WordPress Codex Also read this good piece, why not to use `query_posts()`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, loop, shortcode" }
Rewrite rules priority I'm created URL rules for my theme but some rules not applied in the correct order.. For example: (1) This rule (with only one taxonomy) works fine: /from/(.+?)/?$ => 'index.php?post_type=custom&from=' . $wp_rewrite->preg_index(1) (2) And this another rule, with two or more taxonomies, not working because, the first rule (1) apparently it has higher priority or the regular expression is not well built. /from/(.+?)/to/(.+?)/?$ => 'index.php?post_type=custom&from=' . $wp_rewrite->preg_index(1) . '&to=' . $wp_rewrite->preg_index(2), I used "monkeyman rewrite analyzer" plugin to check my rules and this screenshot shows that this URL: .../from/madrid/to/toledo return the first rule instead the second. What's wrong?? ![enter image description here](
I'd say either change the order, put (2) before (1), or be more specific with the rules. E.g. from/([a-zA-Z]*)/?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rewrite rules, taxonomy" }
Get the title of custom post type in another loop I am in the single-product.php loop and the product has a relationship to an artist post type to which I have the id off the artist. I need to get the_title() from my custom artist post type while in the single-product.php loop. My code is getting the title of the product rather than the artist. My code is below. Can anyone please help? $artistId = get_field('artist'); $postId = get_post($artistId); if ( $postId ): setup_postdata($postId); ?> <span id="chty_17"> <dt><?php the_title(); ?></dt> </span> <?php wp_reset_postdata(); endif;
You can pass a post ID to `get_the_title()`. So instead of using `the_title()` to display it, fetch it first like this. $artist_title = get_the_title( $artistID ); echo $artist_title; You could do that in one line of course but you might need it somewhere else, too.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom post types, loop" }
WP move posts to different path I'm looking to have my blog posts under a subdirectory while keeping pages on the root level. So for example, I want to keep page URLs are like this: mysite.com/pageone mysite.com/pagetwo But I want all blog posts to be under the blog path: mysite.com/blog/postone mysite.com/blog/posttwo How can I do this? Thanks.
Use the permalinks settings under Settings > Permalinks. They only apply to posts, not to pages. Custom structure: /blog/%postname%/
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, urls, blog" }
Adding a <span> within <li>'s from wp_nav_menu() I'm trying to format the list produced by `wp_nav_menu()` so that within each `<li>` is a `<span>` that wraps the text. At first I thought I could accomplish this using the the `items_wrap` argument, but that changes only the enclosing `<ul>`, correct? This seems like it should be simple enough to accomplish. Thanks!
Yes, `items_wrap` is used to to modify or replace the default `<ul>` wrapper. To wrap the individual links inside of that element, simply use `link_before` and `link_after`, like so: wp_nav_menu( array( 'theme_location' => 'some-location', 'link_before' => '<span>', 'link_after' => '</span>', ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "menus" }
removing <p> tags around img, iframes and also scripts I've been working with embeded content and as many already know, wordpress wraps the_content() lines in p tags. So, found this: $content = preg_replace('/<p>\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content); return preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content); When I change "iframe" by "script" it works, but then only for one of them, I need both beacuse the twitter embbeds create a hidden script element wich in turn creates a ghost paragraph.
This should do it and also remove `<p>` tags from images that are linked. Why it removes it from only one `<script>` instance is hard to tell. Would have to see your website code to investigate further. // Remove p tags from images, scripts, and iframes. function remove_some_ptags( $content ) { $content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content); $content = preg_replace('/<p>\s*(<script.*>*.<\/script>)\s*<\/p>/iU', '\1', $content); $content = preg_replace('/<p>\s*(<iframe.*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content); return $content; } add_filter( 'the_content', 'remove_some_ptags' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "the content, embed" }
Remove post type filter added by the plugin in the final query I am querying the post types based on the custom post type, but when printing the final query it also includes the `post_type='tribe_events'`, which is due to plugin using for the events. But I have added the following parameters only in the query: $args = array( 'post_type' => 'mycustomepost', 'posts_per_page'=>1 ); How to remove the events post type filter from the query?
The best course of action would be to prevent the plugin from doing something you don't want. If for some reason this is not possible you can use the filter `pre_get_posts` to change the query before it is executed, like this: add_action( 'pre_get_posts', 'wpse239465_force_post_type', 9999); function wpse239465_force_post_type () { $query->set('post_type', 'mycustomepost'); } Note that this will force the post type on all your queries, given that the priority of 9999 guarantees it is the last filter applied and there is no condition attached to `$query->set`. So you may at least want to add some conditional tag.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, filters" }
Automatically Add Specified Value to Attachment Metadata upon Upload I am trying to create a function that automatically adds a value to the attachment metadata (if it matters, on Audio uploads). For example, I want to add a value of 'artist' and output it as my own specificity (for the sake of the example, just simply 'test') I've tried numerous things but each one, thus far, has not worked (and outputs an unspecified error upon uploading the media). Here's a couple things I've tried: function auto_update_audio_meta($post_ID) { add_post_meta( $post_ID, 'artist', 'test'); } add_action('add_post_meta', 'auto_update_audio_meta'); I've also tried hooking to `update_post_metadata`, and variations such as function auto_update_audio_meta() { wp_update_post_meta( $post->ID, 'artist', 'test'); } add_action('update_post_metadata', 'auto_update_audio_meta', 10, 5); What am I doing wrong?
You're close! Try using these hooks instead. // Add post meta to new audio uploads. function auto_update_audio_meta( $post_ID ) { if ( wp_attachment_is( 'audio', $post_ID ) ) { add_post_meta( $post_ID, 'artist', 'test' ); } } add_action( 'add_attachment', 'auto_update_audio_meta' ); For attachment updates // Update post meta to updated audio uploads. function auto_update_audio_meta( $post_ID, $post_after, $post_before ) { if ( wp_attachment_is( 'audio', $post_ID ) ) { update_post_meta( $post_ID, 'artist', 'test' ); } } add_action( 'attachment_updated', 'auto_update_audio_meta', 10, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "functions, actions" }
Wordpress remove EXIF Data from specific Thumb Is it possible to **hook** in to action when uploading and resizing specific size added by `add_image_size( 'mini-placeholder', 32 )` for image in Wordpress, and remove EXIF Data, and set quality of this one to minimum (10/20%)? I want to achieve small thumb under 1kb (the goal is smallest as it is possible).
Assuming you are using ImageMagick (the WP standard) as your library there is a filter called `image_strip_meta` which controls whether the EXIF data must be preserved. Normally you would just use a boolean to do an overall setting, but you could easily make that a function like this: add_filter ('image_strip_meta','wpse239481_conditional_strip') function wpse239481_conditional_strip { if (...condition ..) return true else return false; } The problem is in the condition. You would need to access the current thumbnail label, which doesn't trickle down from the multi_resize method that sets thing going. However, the target width and height are known in the resize function where the filter resides. Still, you can't access those dimensions inside the filter unless you hack the core to make this instance of `apply_filters` pass parameters. Unless of course, someone smarter than me knows a trick.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "php, images, thumbnails" }
How to catch and modify custom field values when a page is updated I'm trying to find how to intercept the values in some custom fields on a page when they are being saved. I have searched and found out how to add a hook to the functions file to get the standard content fields, but so far haven't worked out how to do the same for custom fields. I'm using ACF Pro with flexible content fields, so the actual values come through as mutli-dimensional arrays. The code that I am using is at the bottom. This code successfully modifies the standard 'post_content' field before saving. Basically I want to do the same for various custom fields. Any ideas? function save_my_post( $content ) { global $post; if( isset($post) && get_post_type( $post->ID ) == 'post' ){ $content['post_content'] = function_to_manipulate_the_content(); } return $content; } add_filter( 'wp_insert_post_data', 'save_my_post' );
It all depends on how your "custom fields" are saved. If you store the values as post meta then you would have to call the update_post_meta function to update them on wp_insert_post_data. In the example below Im setting the post meta "my_meta_key" with the string value "my_meta_value". function save_my_post( $content ) { global $post; if( isset($post) && get_post_type( $post->ID ) == 'post' ){ update_post_meta( $post->ID, 'my_meta_key', 'my_meta_value' ); } return $content; } add_filter( 'wp_insert_post_data', 'save_my_post' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "hooks, save post, wp update post" }
Set Post Format if find a string in title or post content I'm working with ITFFF in order to create posts, but I have a problem with the "Post Format". I need to change the Post Format to image if there are some specifics strings in the title or post content.. I was reading the forum and collecting some codes to create a this.. but it isn't working. This is my code: add_action( 'save_post', 'CambiarPostFormat' ); function CambiarPostFormat( $postID ) { $a = get_the_title( $post_id ); if ( has_post_format( 'image', $postID ) || srtpos($a, 'imagenes') !== false) return; set_post_format( $postID, 'image' ); }
You are using `$post_id`, but you have passed the post ID as `$postID`. As a result `$a` is always empty. Even if it weren't empty, there is no PHP function `srtpos`. It's `strpos` and you could have more straightforward logic to execute `set_post_format`. Wrapping it up: function CambiarPostFormat( $postID ) { $a = get_the_title( $postID ); if ( !has_post_format( 'image', $postID ) && strpos($a, 'imagenes') !== false) set_post_format( $postID, 'image' ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, php, post formats" }
Date Archives' Permalinks under Category folder I have my WP put under /wp and then my-blog (which is an category, with the slug name 'my-blog') is set to access from (via the plugin 'Top level category') /my-blog/ everything seems fine, except my date-archives goes directly under the root as /2016/09/ which is the default permalink. However, I would like those date-archives of above category permalinks as: /my-blog/2016/09/ Is it possible to change rewrite rules to work? Please help.
Thats posible by using Custom Structure of the permalinks like below: /%category%/%year%/%monthnum%/%postname%/ You will also be able to get a monthly archive of the category by going to: /%category%/%year%/%monthnum%/ like: www.yoursite.com/my-blog/2016/09/
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, archives, rewrite rules" }
List pages including both parent and child pages I'm currently listing WordPress pages and child pages on a side widget using the following code. <ul class="side-links"> <?php wp_list_pages( array( 'title_li' => '' ) ); ?> </ul> This lists all of my WordPress pages, if I add the following code `'child_of' => $id` into the array I get the children on the parent page, If I go to a specific child page the list will not be displayed. I just need the list of child pages to be displayed on all pages including parent and child pages. If it helps I've placed the following `wp_list_pages` function on this page in the following theme. <
Here is the code with help form @Rarst that shows children page links on both parent and child pages. <?php global $post; $children = get_pages( array( 'child_of' => $post->ID ) ); $hasChild = (count( $children ) > 0 ); $page_id = ($hasChild) ? $post->ID : wp_get_post_parent_id( $post->ID ); wp_list_pages( array( 'title_li' => '', 'child_of' => $page_id, ) ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "links, wp list pages" }
How to load a CSS file into WordPress admin area using Child Theme? I want to load a css file into **Wordpress Dashboard** using child theme?
You need to use `admin_enqueue_scripts` hook to load CSS in admin area. This goes in your themes `functions.php`. Assumed that your file is at `child_theme_path/css/admin-css.css` function wpse239532_load_admin_style() { wp_enqueue_style( 'admin_css', get_stylesheet_directory_uri() . '/css/admin-css.css', false, '1.0.0' ); } add_action( 'admin_enqueue_scripts', 'wpse239532_load_admin_style' );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "wp admin, child theme" }
How to link a Page with an anchor tag in WordPress I want to link a Page with an anchor tag and send some data through a URL from another Page. I have made a page template and I tried to link to it, but it does not work. I can open the page by creating menu link but I can't open it directly using the link. My anchoring code is: <p><?php echo $post_excerpt;?> <a href="<?php echo add_query_arg( array('id' => $id), home_url()."/fullpost/" ); ?>" style="color: #4e2011;">Read More...</a></p> Now the problem is when I click on _Read More_ the URL works fine, `id` is added to the URL, but I still end up on the same page, not my desired page. I have Googled several times about this problem but haven't found a solution.
Actually the problem was with my page settings. If someone wants to link a php file to another php file by anchor tag (a href="....") and wants to send some data through URL, he/she must has to make the targeted php file a page template. Like this <?php /*** Template Name: Gallery ***/ Then he/she has to create a new page from the dashboard with this page template. Only after this process the link will work properly. I didn't create the page from dashboard.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php" }
Attaching a pdf to Contact Form 7 e-mail via functions.php I'm trying to attach pdf files to an e-mail manually and I did some research on the topic and found this code: add_action('wpcf7_before_send_mail','send_pdf'); function send_pdf( $cf7 ) { $id = $cf7->id(); if ($id==2399){ $submission = WPCF7_Submission::get_instance(); $submission->add_uploaded_file('pdf', get_template_directory().'/pdf/test.pdf'); } } The strange thing is that after the email is sent, the file and the folder are deleted but nothing is attached. I'm using a theme and a child theme, and the folder is put in the main theme directory. Anyone ideas?
I've found what's been missing in the code. You have to add this also: add_filter( 'wpcf7_mail_components', 'mycustom_wpcf7_mail_components' ); function mycustom_wpcf7_mail_components( $components ) { $components['attachments'][] = get_template_directory().'/pdf/test.pdf'; return $components; } Now everything is working fine and the file is attached to email without the need to add fields in the contact form.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, email, plugin contact form 7, pdf" }
Replace Underscore (_) on Space ( ) I use the plugin "Auto Post With Image Upload" For example I load an image with name "Image_Name" then plugin creates a post with name "Image_Name" Now the question: How to remove Underscore (_) in post title Tell me "where to dig"? I know that there are such a function "str_replace". Where apply it? Here is a piece of code: $postData = array( 'post_title' => $attachment->post_title, 'post_type' => 'post', 'post_content' => $image_tag, 'post_category' => array('0'), 'post_status' => 'publish' ); P.S. I not quite understand php
You are correct, you need to use `str_replace`. See details here So the correct code would be: $postData = array( 'post_title' => str_replace('_', ' ', $attachment->post_title), 'post_type' => 'post', 'post_content' => $image_tag, 'post_category' => array('0'), 'post_status' => 'publish' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, title, customization, underscore" }
Batch update menu_order attribute alphabetically Is there a way to batch update the page order attribute of all children of a specific parent, each time a new child is added? More simply, is there a way to loop through pages and change the sort attribute so they are alphabetical? For instance.... * Page Title A - sort order 0 * Page Title C - sort order 0 * Page Title B - sort order 0 Would become... * Page Title A - sort order 1 * Page Title C - sort order 3 * Page Title B - sort order 2 And would ultimately be displayed in the admin as... * Page Title A - sort order 1 * Page Title B - sort order 2 * Page Title C - sort order 3
Hopefully this helps someone else Dont forget to change "your_post_parent_id_here" with the parent id of your choosing. global $wpdb; $wpdb->query( 'SELECT @i:=-1' ); $result = $wpdb->query( " UPDATE wp_posts SET menu_order = ( @i:= @i+1 ) WHERE post_parent = 'your_post_parent_id_here' ORDER BY post_title; " );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, pages" }
Images not showing after path specified in header.php I am developing a WordPress site based on a theme developed using Twitter Bootstrap. I have a banner image specified in my `header.php` which is loaded at the top of every page. **Added the image path** After having made the requisite changes in the `header.php` to include the path <img src="<?php echo get_stylesheet_directory();?>/images/headerbg.jpg" alt="the image is not showing" class="img-responsive center-block"/> _My image still does not show and the alt tag is shown_ ![enter image description here]( **Confirming the image path is correct and working** _When directly using the computed code from the browser, I am able to access the image:_ ![enter image description here](
Use `get_stylesheet_directory_uri()` instead of `get_stylesheet_directory()`. <img src="<?php echo get_stylesheet_directory_uri();?>/images/headerbg.jpg" ..../> `get_stylesheet_directory_uri()` returns URI of the stylesheet directory where as `get_stylesheet_directory()` returns the _path_ on the server to the stylesheet directory.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme development" }
Custom Query to search through categories I'm trying to display categories as search result items on top of the `search.php` results. There doesn't seem to be a standard WordPress function or WP Query to search through categories, so I figured I'd write my own MySQL statement. SELECT DISTINCT t.*, tt.* FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('category') AND (t.name LIKE 'hout') ORDER BY t.name ASC In the above example, the search term is "hout". However this doesn't seem to return any results. Can you see anything wrong with my query? Or do you know of another way I can include categories as search result items?
It sounds like you're looking for the `get_terms()` function that's a wrapper for `WP_Term_Query`. There you can e.g. use the `name__like`, `description__like` or `search` parameters. **Example:** Here's what kind of `WHERE` query they generate: 'name__like' => 'hout' >>> (t.name LIKE '%hout%') 'description__like' => 'hout' >>> tt.description LIKE '%hout%' 'search' => 'hout' >>> (t.name LIKE '%hout%') OR (t.slug LIKE '%hout%')
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, query, search, mysql" }
Best way to ping for the API changes in the wordpress? I am importing the posts into the wordpress from external API's , i have created the plugin for this, posts are imported successfully. but now i am going to implement auto check for the new API changes and if new posts exists on the API then import that post into the wordpress. What is the best way to implement this ? Can i request the API URL after a certain amount of time ?
Yes you can use wp_schedule_event to trigger a hook used in your plugin to request the API URL after a certain amount of time.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, api" }
Is it possible to change the admin posts per page view? In the admin panel (backend) when you go to "posts" it shows you a pagination (in my case with 29 posts per page). Is it possible to change to posts per page number for a specific post type? Thanks.
This is a wordpress core feature on most (all?) list type admin screen, you just go to the "screen options" (right below the admin bar) and change the "number of items per page" setting. This setting is stored per user per screen therefor each user can customize it to whatever works best for him. IMO this is all you need, and there is no need to do any coding, but if you want to have different default value than 20, you should investigate where the value is saved in the user meta and set it upon plugin activation.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "posts, admin, pagination" }
A better way to override plugin's JS files? I'm modifying some functionality of a theme i'm using, which already set up a `.js` file inside a plugin to handle the paypal checkout process. I had to modify the code so I renamed a few elements and basically copied the old js file to a new file and made the changes. It works and everything is fine, but I wonder if there's a better way to do it in Wordpress? It doesn't feel right to modify so much just so I could change a few lines of code inside. Thanks!
Extending the above comment: Directly changing the files of the plugin or theme is not a good practice as once the plugin/theme is updated, you will loose the changes. Instead use child theme in case of themes and hook to required actions in case of plugins. In your case since you are only changing the script in plugin and they might have enqueued(they should be) with `wp_enqueue_script` hooked to `wp_enqueue_scripts`. You can dequeue that script using `wp_dequeue_script` all you have to do is findout the script handle from the original plugin. Then you need to enqueue the changed script.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "plugins, javascript" }
Wordpress Attachments with old images I have a situation where I need to get all the images used in some kind of post. Now the problem is that attachments is saved only when I upload new image, if I use some other image which was already uploaded, it doesn't change my post attachment. So even if I change all the images in post, Wordpress still see that my post attachment is that very first uploaded image, not the new one. Any ideas how should I rewrite the attachments even if image is not a new one?
To get all featured images belonging to a certain post type, you'd have to get all those posts and the loop through them to get the featured image. Like this: $query = new WP_Query( array( 'post_type' => 'yourposttype', 'posts_per_page'=>-1, )); $thumb_list = array (); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $thumb_list[] = get_post_thumbnail_id(); } wp_reset_postdata(); // resetting for the main query }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, attachments, media, media library" }
Require WP login for outside access I am building an intranet site for my company. The goal is to have people within the building have open access but outside the building require a username and password. I have looked through a couple options with using an htaccess file, or possibly a combination of plugins. Can anyone point me in the direction to do this. I was thinking of doing something along the lines of IP address based requiring of WP authentication but I have not figured out how to accomplish that as yet.
Assuming you're using Apache and don't specifically need users to log in via WordPress, you can use HTTP Authentication. This Stack Overflow thread is what you're looking for. Also, check out the documentation for Apache's HTTP Authentication and Access Control.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp login form" }
Check if tag contains posts Hey I am trying to come up with some logic for if a tag contains any posts I found the below code for a category <?php if (get_category('17')->category_count > 0) { ?> <?php } ?> I have tried modifying it with `get_tag` in place of `get_category` which did not work. I thought this could be because `category_count` can't be used with the tag taxonomy but I couldn't find any tag equivalent in the codex Thank you
You can use: <?php if (get_tag('17')->count > 0) { ?> <?php } ?> `get_tag` is basically a `get_term` with taxonomy `post_tag` and `get_term` returns `WP_Term` object on success, `WP_Error` on error. `WP_Term` has property `$count` which has object count for the term in process.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Language file doesn't work I'm trying to translate a WordPress template. I went to language files, there were already 3 languages so I copied one of it (es_ES.po in my case), then opened that copy with Poedit and started translating to my language (Arabic). After finishing the translation, I changed the WordPress language from the dashboard, but the language didn't change in the template, it kept being English. Any idea why this happens? These are the language instructions from functions.php: load_theme_textdomain( 'mundothemes', get_template_directory() . '/idiomas' ); $locale = get_locale(); $locale_file = get_template_directory() . "/idiomas/$locale.php"; if ( is_readable( $locale_file ) ) require_once( $locale_file ); and here is a screenshot of the language folder: ![enter image description here](
Can you please try this code in your theme functions.php and tell us what locale do you get on the screen? die( var_dump( get_locale() ) ); If `get_locale()` value is not `ar_AR` then that explains why it won't load your translation. and you may need to adjust/change the locale file name ( the .mo file ) in your language folder.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "translation" }
How to edit an existing wordpress.org site I need to edit someone else’s wordpress.org site They have already gotten hosting and have downloaded wordpress to their host I am meant to design their site for them (or try to anyways). They made me a log in and password so I can edit their site. My question is: 1. Do I need to download wordpress.org to edit their site or can I just go to wordpress.org/login and log in and edit the changes there? (I’ve already tried logging in with their u/n and /pw but it doesn’t seem to be working. Not sure if I’m doing something wrong) 2. If I do have to download wordpress myself how do I then go an edit THEIR website? From the tutorials I’ve watched about downloading wordpress.org to a mac, you create your database (or site) right then and there. What happens if someone else has already created their site and has it linked to a domain? Thanks everyone for your help. I’m such a noob at wordpress!
Just do a search for "edit wordpress theme". It sounds like it's the "theme" you want to change. You can either modify what they have now, or you can make your own theme from scratch. If they just want some changes to the theme they have now you'll probably just want to modify a theme, but I'd say learning how to build a theme from scratch would help you understand how it works.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "installation" }
is_page_template not working as expected I'm trying to serve different headers based on what type of page the user is on. This is my code. <!-- IF HOME --> <?php if ( is_front_page() && is_home() ) : ?> <?php get_template_part( 'template-parts/headers/home-header' ); ?> <!-- IF TEMPLATES --> <?php elseif ( is_page_template('archive-mobile_photo.php') ) : ?> <?php get_template_part( 'template-parts/headers/home-header' ); ?> <!-- IF POST --> <?php else : ?> <?php get_template_part( 'template-parts/headers/zine-header' ); ?> <?php endif; ?> What's weird is that the homepage and post pages are working fine, but the check using `is_page_template()` isn't working. I have the query monitor plugin and it's confirming the page is the `archive-mobile_photo.php` template. I'm pretty new to WordPress and I'm at a total loss.
It looks like you're checking if you're on the `mobile_photo` post type archive with this line: <?php elseif ( is_page_template( 'archive-mobile_photo.php' ) ) : ?> If that's indeed the case, use `is_post_type_archive( $post_types )` instead: <?php elseif ( is_post_type_archive( 'mobile_photo' ) ) : ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom post types, php, templates, page template, conditional tags" }
How to Add Custom New Published Post Counter Icon on Top of the Wordpress Site I have a technology blog based on wordpress. I would like it to show a icon on top of the menu bar to show new post counter for today. Just like Android Authority website (check here < Am a newbie here and i dont know a lot about CSS and Function.php the only thing i know is basic wordpress editing skills. I've tried google about it, but without any luck at all. Any ideas on how to do it or the function.php file i can add in my theme child theme am using bunchy wordpress theme) Thanks in Advance You For Your Help
Check out code below. Function returns a number of posts published with todays date. You just have to modify a navigation a little bit to add this number counter to a menu bar. echo "<h1>Today is: " . date("Y-m-d") . "</h1>"; function published_today() { $counter = 0; $posts = get_posts(array('numberposts'=>-1)); foreach ($posts as $post){ if (get_the_time('Y-m-d', $post->ID) === date("Y-m-d")) { $counter++; } } return "Posts published today: " . $counter; } echo published_today();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, plugin development, icon" }
wp_get_post_terms() returns WP_Error in functions.php but in template it works $my_post_id = 644; $areas = wp_get_post_terms( $my_post_id, 'area-trabajo' ); var_dump($areas); This code, in functions.php, returns: object(WP_Error)#3178 (2) { ["errors"]=> array(1) { ["invalid_taxonomy"]=> array(1) { [0]=> string(20) "Taxonomia no válida" } } ["error_data"]=> array(0) { } } But in a template, returns the expected result: array(1) { [0]=> object(WP_Term)#7194 (11) { ["term_id"]=> int(150) ["name"]=> string(13) "Restauración" ["slug"]=> string(12) "restauracion" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(150) ["taxonomy"]=> string(12) "area-trabajo" ["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(1) ["filter"]=> string(3) "raw" ["term_order"]=> string(1) "0" } } What could be the reason that in the functions.php returns invalid_taxonomy?
If you dump the code into `functions.php`, then the custom taxonomy hasn't been registered, because it isn't recommend to register custom taxonomies earlier than the `init` hook. Running the code within the template hierarchy files should work, because it's later than `init`. If you want to run it within the `functions.php` file, make sure to hook it accordingly.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "functions, taxonomy" }
Exclude posts from featuring I'm trying to hide posts from a specific category from being featured. Currently, the section shows featured posts from all categories. I need to exclude posts from a category (with category name not by id). $args = array( 'posts_per_page' => 1, 'meta_key' => 'meta-checkbox', 'meta_value' => 'yes', ); $featured = new WP_Query( $args );
**Excluding specific categories from WP_Query** This is in the codex. You can exlclude specific categories from WP_Query. Where array(2, 6) are IDs for categories to be excluded in this example. $query = new WP_Query( array( 'category__not_in' => array( 2, 6 ) ) ); See the codex: < **NOTE: If you are trying to exclude category by the name of category** First you would do this to find the category ID by providing category name. $category_id = get_cat_ID( 'My Category' ); then add the returned `$category_id` in your WP Query arguments it would look like this: $query = new WP_Query( array( 'category__not_in' => array( $category_id ) ) );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "posts, wp query, categories" }
Customize Wordpress Core Template I used the `paginate_links()` function to retrieve pagination and everything works fine. It returns every link as `a` anchor tag it is also fine if we want links inside `<li></li>` we can specify return type as `array` and then loop to add links to `<li></li>`. but what is the solution for current page link it return a span tag but i want wordpress to give me an anchor tag with `href="#"` attribute. i google but not find any solution instead i get understand from where this template is generating it's located in `general-template.php` file and it's easy to just replace html template there and that's it. but it is not permanent solution nor good wordpress development. **cons of doing so** 1) whenever wordpress will update my changes will lost. 2) it's not effective in just my theme it will disturb core template anyone can help me out what is the better way to do so..?
Since it isn't pluggable, you could define a replacement function in your theme. In your theme's `functions.php` file, copy the core `paginate_links()` function, rename the function - perhaps `my_paginate_links()`, modify the source code so it creates the anchor tag you need, and then call your new function wherever you need it in the rest of the theme.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "pagination" }
Getting the ID of a meta box I'm wanting to change the display title of a meta box when editing a custom post. I want to try this solution here: How to change the title of a Meta Box on a specified Custom Post Type? Where I'd be removing the meta box and then re-adding it with a modified title. However, I don't have the ID information of my meta boxes and am having trouble finding them. Is there a way to get a list of ID's of meta boxes? I've looked into the global variable `$wp_meta_boxes`, but I couldn't figure out how to list the ID's. A bit more information: I didn't create the meta boxes originally. I created custom taxonomies for a specific post type, and Wordpress automatically created the meta boxes that allow you to tag those custom taxonomies while editing my custom post.
Here's what I would do in order to get the ID of the metabox, 1. In the _Dashboard_ where the meta boxed are located, open up the _Screen Options_ tab on the upper right corner 2. Open up your browser's developer tool (ex: Chrome) 3. Use the element selector (![]( and select the checkbox label that is listed in the _Screen Options_ , like so: ![]( 4. The element will be selected and you should see something similar: ![]( 5. For each `<label for=` tag, you will find the ID's of each meta box, for example: * `dashboard_right_now` * `dashboard_activity` * `dashboard_quick_press` * `dashboard_primary` * `wp_welcome_panel` From there, you can continue with the code that you found in a previous question with the ID that you need.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "metabox, id" }
'Thumbnail' and 'Medium' Image sizes are different than expected In a typical WordPress installation, the size of the `thumbnail` image is 150x150 and `medium` image is 600x400. I'm theme developer and I have one client which has different sizes for these. The `thumbnail` size is 150x100 `medium` size is 300x200. How can this be? Can this be overwritten in the WordPress core somewhere, or in the database? My theme doesn't overwrite these but adds new/custom image sizes which shouldn't have any impact on the default ones. I never faced this issue before. For all other clients, everything is working fine. I would really appreciate some thoughts on this.
The `thumbnail`, `medium`, and `large` sizes can all be configured by the user under _Settings > Media_. Different installs can have different settings. The default size for the `thumbnail` size is 150x150, `medium` is 300x300, and `large` is 1024x1024.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "thumbnails" }
How to register script with null value for version? Can someone explain the version argument in `wp_register_script()`? According to the codex it is `added to the URL as a query string for cache busting purposes`. It also says if the `$ver` argument is set to `null`, no version is added and if `false`, the currently installed version of WordPress is added. How do I set the `$ver` argument to `null`? I thought I had in the code I'm using below but it's adding the currently installed WordPress version as the version number. function add_ajax_script() { wp_register_script('ajax-implementation', '/wp-content/themes/codilight-child/scripts/ajax-implementation.js', array('jquery'), '', false); wp_enqueue_script('ajax-implementation'); } add_action( 'wp_enqueue_scripts', 'add_ajax_script' );
You literally specify the version number as `null`: function add_ajax_script() { wp_register_script( 'ajax-implementation', get_stylesheet_directory() . '/scripts/ajax-implementation.js', array('jquery'), null, false); wp_enqueue_script('ajax-implementation'); } add_action( 'wp_enqueue_scripts', 'add_ajax_script' ); An empty string, `''` is not the same thing as `null`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp enqueue script, wp register script" }
Favicon causes mixed content warning over SSL I have the following favicon loading via header.php: <link rel="shortcut icon" type="image/x-icon" href="<?php echo esc_url( home_url( '/wp-content/themes/themename/img/favicon.ico' ) ); ?>"> My site has an SSL certificate installed. Google Chrome loads the each page over SSL perfectly, but Firefox flags a mixed content warning. I can see via the source (both in Chrome and Firefox), that the favicon is being served via http. I can't work out why this is happening.
After a little more reading via the WordPress Codex, I discovered that I was calling the favicon incorrectly. It should be called like this: <link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri(); ?>/favicon.ico" /> Using `get_stylesheet_directory_uri()` checks for SSL.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "ssl" }
way to include own functions independent of theme I know how to include my own functions by writing them into the theme's `functions.php` and enqueuing them, or by including a php file containing all that in `functions.php`. But that is always bound to the used theme. If I switch to another theme, I always have to copy that code to the new theme's `functions.php` Is there any way around that - a place/file where I can define and enqueue scripts that remain valid across all themes? (without loosing it when WP is updated)?
This is not quite simple (as copying and pasting into new functions.php :D), but you can create a plugin that will load this every time. A (very) good and simple guide can be found here. ## Addition by Original Poster (johannes) I created a plugin for that: 1. I created a simple php file and put it into `wp-content/plugins`. It looks basically like this (i.e. it contains the plugin name, description, author etc. and the function I want to use in my site across all themes): <?php /** * Plugin Name: Function-Includer * Plugin URI: my URI * Description: my description * Version: 1.0 * Author: johannes * Author URI: my URI */ [... code of my function ...] ?> 2. Then I went into the WP admin backend, to the plugin page, where that plugin is listed as "Function-Includer" and activated it. 3. Done - the function is available everywhere in my site now.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "theme development, wp enqueue script" }
Certain header elements not served over https I have forced SSL on each page of my site using WordPress HTTPS. This works perfectly and isn't throwing up any mixed content warnings. However, when I visit the page source, I can see a whole bunch of resources being served over http in the header. These are not resources that I control, but what I assume to be coming from the WordPress core. Here they are: <link rel="profile" href=" <link rel="alternate" type="application/rss+xml" title="Website &raquo; Feed" href=" /> <link rel="alternate" type="application/rss+xml" title="Website &raquo; Comments Feed" href=" /> <link rel=' href=' /> <link rel='shortlink' href=' /> <link rel="alternate" type="application/json+oembed" href=" /> <link rel="alternate" type="text/xml+oembed" href=" /> What are these elements doing and should I be concerned that they are not being served over https?
I'm not sure about the first one, the profile, but the `rel="alternate"`s and the `rel='shortlink'` provide different formats for different readers, like XML and RSS feeds. These should be generated by your site URL. In your dashboard, go to Settings > General, and make sure you're using https:// instead of http:// in the URL. You may then need to clear your site cache to see the change.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "ssl" }
Synchronise Renewals on existing subscriptions I have a site that uses woocommerce together with subscriptions plugin. And I have recently turned on "Synchronise Renewals", I see that it works great for new people signing up for a subscription. But the previous subscriptions are not renewing to the specific day, but is renewing on the same day they signed up.. How can i make my precious subscriptions renew on the same day? Would a solution be to manually change the date in "Next payment" field in the Billing schedule box on each subscription? Will that make it renew every monday if the date is on a monday?
Yes a solution for this is to manually change the date in "Next payment" field in the Billing schedule box on each subscription A subscription can be unsynchronized by changing the next payment date to a day not aligned with the synchronization schedule. For example, changing a weekly subscription synchronized to Mondays to have the next payment processed on Wednesday will mean all future payments will be processed on Wednesday. This is because future payments are calculated based on the past payment and renewal synchronisation is only calculated and applied to the first payment.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, subscription" }
Trying hard but can't hide featured post/page from grid i have a theme where first a featured post is displayed. then there is a grid of posts. Problem is grid also displays the featured post. So, featured post appears twice. Question is **how to hide featured post from grid?** Note that a custom meta box has been added to mark post/page as featured. loop that starts featured section is as below... if ($featured->have_posts()): while($featured->have_posts()): $featured->the_post(); ?> grid is formed from below code... (i need to hide featured post from this grid) <?php $counter = 1; $grids = 3; global $query_string; query_posts($query_string . '&caller_get_posts=1&posts_per_page=12&cat=-' . get_cat_ID( 'News' )); if(have_posts()) : while(have_posts()) : the_post(); ?>
wp section of stackexchange really seems half dead. you rarely get issue sorted. have_posts checks whether there is any post, so add another condition that checks whether the post is featured or not. if(have_posts()) : while(have_posts()) : the_post(); replace above with below if(have_posts() && the_post() != $featured) : while(have_posts()) : the_post();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts" }
remove permalink "front part" for custom post type Let's suppose I have CPT "event". In register_post_type, I've set 'slug' => 'event' Then, in Wordpress settings I've set following Permalink structure Custom: The problem is, URL for my "Event" CPT is www.domain.tld/news/event/<event-name> and I want www.domain.tld/event/<event-name> how can I achieve that? Thanks
Use the argument: 'rewrite' => array( 'slug' => 'event', 'with_front' => false, ) The 'with_front' flag controls whether to use the front part you've defined.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, permalinks, url rewriting" }
Read More showing only on first post I created a new menu item which only pulls posts categorized “Webinars” but when I visit the Webinar category page, only the first post excerpt gets a “Read More” button. What do I have to do so that all post excerpts in this blog category get a “Read More” button?
There are only 2 posts on that page, so there's not a lot to go on here, but it looks like there is not enough text to warrant a _Read More_ button for the second post. By default, WordPress has an excerpt length of 55 words (looks like that's in effect on your site). The second post isn't long enough to have an excerpt so the full post is shown. You can change the number of words in the excerpt to something shorter. Add this code to your theme's `functions.php` file: /** * Filter the except length to 20 words. * * @param int $length Excerpt length. * @return int (Maybe) modified excerpt length. */ function wpse240108_custom_excerpt_length( $length ) { return 20; } add_filter( 'excerpt_length', 'wpse240108_custom_excerpt_length', 999 ); Alternatively, you can add a `<!--more-->` tag within the content generate your own excerpt rather than relying on WordPress to generate the excerpt.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, blog, read more" }
How to detect and make links nofollow in author description I have this code in my `author.php` file: $buffy .= '<div class="td-author-description">'; $buffy .= get_the_author_meta('description', $author_id); $buffy .= '</div>'; How can the `$buffy` string be parsed so that links within the author description will have the `rel="nofollow"` attribute set automatically?
This is really more of a general PHP question, but this will do the trick: $author_desc = '<div class="td-author-description">'; $author_desc .= get_the_author_meta( 'description', $author_id ); $author_desc .= '</div>'; $dom = new DOMDocument; $dom->loadHTML( mb_convert_encoding( $author_desc, 'HTML-ENTITIES', 'UTF-8' ) ); $sxe = simplexml_import_dom( $dom ); // Process all <a> nodes with an href attribute foreach ( $sxe->xpath( '//a[@href]' ) as $a) { if ( empty( $a['rel'] ) ) { $a['rel'] = 'nofollow'; } else { $a['rel'] .= ' nofollow'; } } $author_desc = $dom->saveHTML(); $buffy .= $author_desc; Replace the original code in your question with the code in this answer (this is based on the full code that you posted here). Code adapted from this answer on Stack Overflow. Encoding fix via this post.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Adding Buy Button to Blog Post (Woocommerce) I'm using Woocommerce. Is it possible to add a buy button to a blog post that features a specific product? Can it be added to a blog post with a shortcode perhaps (so that it’s easily do-able by the client)? We’ll publish a blog post about a product, add some videos, images and text, and then include a buy button. The buy button should add the specific product to the cart. If it isn’t possible at all, any recommendations on how to implement this? Thanks for your help.
WooCommerce by default supports shortcodes that can be embedded in a post, one of those is a 'Add to Cart' shortcode. See the WooCommerce documentation at <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic, blog" }
Add a post meta key and value only if it does not exist on the post I have a custom field on a WooCommerce product, and I am entering the ID of another product into it. When saving that product, I am adding a meta field to the product that was inputted, creating a "link" between them. I have this working fine, but the issue is that it adds it even it is already there. function part_fits($post_id){ global $post; global $product; $current_diagram_id = get_the_ID(); if( have_rows('product_association') ): while( have_rows('product_association') ): the_row(); $single_part_id = get_sub_field('part'); add_post_meta($single_part_id, 'part_fits', $current_diagram_id); endwhile; endif; } Is there a way I can check if that exact key and value already exists and only add it if it does not?
It looks like you need to use `update_post_meta()` < **Source: WP Codex** The function update_post_meta() updates the value of an existing meta key (custom field) for the specified post. **This may be used in place of add_post_meta() function.** The first thing this function will do is make sure that $meta_key already exists on $post_id. If it does not, add_post_meta($post_id, $meta_key, $meta_value) is called instead and its result is returned. Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure. It also returns false if the value submitted is the same as the value that is already in the database.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom field, post meta" }
Adding variable to get_template_part <?php get_template_part( 'template-parts/component-page/component-$variable); ?> What is the correct way to add a variable to where I currently have $variable?
It looks like you're just trying to concatenate a string, so it can be done like this: <?php get_template_part( 'template-parts/component-page/component-' . $variable ); ?> Or you could use string interpolation (note the double quotes used here): <?php get_template_part( "template-parts/component-page/component-{$variable}" ); ?> Alternatively, `get_template_part()` can take two parameters, `$slug` and `$name`: <?php get_template_part( 'template-parts/component-page/component', $variable ); ?>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "templates, page template, variables" }
Theme's Options Page included with require_once *.php in functions.php not visible anymore I want to seperate my Option-Page functions and functions.php. Therefore i moved Option-Page functions to another file "includes/options.php". Including the file with require_once("includes/options.php") does not work **anymore** (I am absolutely sure that it worked in past), but require_once("includes/options.inc") is working. When should i use *.inc files and when *.php files? Especially when theme or plugin developing. I have done same as here: Organizing Code in your WordPress Theme's functions.php File?
If you are editing theme files use `get_template_directory` to retrieve the php files. try the code below in your `functions.php` file. require get_template_directory() . '/includes/option.php';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, theme development" }
WP_Query doesn't accept Category ID I am trying to make a Query wich only shows images, but I have the problem that it doesn't work with the custom post types category ID. Here my code: $catid = get_term_by( 'name', $name, $taxonomy ); $catid = $catid->term_id; $args_query = array( 'cat' => &catid, 'posts_per_page' => 6, 'post_type' => 'video', 'hide_empty' => 1 ); $query= new WP_Query( $args_query ); if ( $query->have_posts() ) { while($query->have_posts()) { $query->the_post(); ?><?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } else { echo '<p>this post does not have a featured image</p>'; } } } else { echo '<p>No post images found</p>'; } Anybody knows a fix for that problem? By the way I am using a Shortcode to get $name and $taxonomy
If your category is custom taxonomy you'll have to use tax_query in you `WP_Query()`. See: < I guess it's a typo that you have `&catid` instead of `$catid`. Edit: Something like: $args_query = array( 'posts_per_page' => 6, 'post_type' => 'video', 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'term_id', 'terms' => $catid ) ) ); Note: Check for typos since I have not tried or tested this.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugin development" }
Promoting child theme to stand alone I have developed a website using a fully fledged theme packed with tons of bloatware and custom functions/widgets I am not using. The package is slow, and 95% of CSS (1MB!!!!) and Javascript is never used by the child theme. This is why I am thinking about unlinking the child theme from the parent and promote the child theme as a standalone theme. However this requires "walking" through PHP code, scripts and CSS to verify what is being used before trimming. What steps would you take, generally speaking, to achieve this?
Start with "view source" of rendered HTML and then work backward from that, building a new theme by pulling whatever css, php files and functions from the parent as needed. (footnote - thank you for the pointer to the 'dust me' utility, I will check that out).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "child theme, performance" }
Modify page title format (when using title-tag) Currently my page titles are handled by WordPress, in a call to wp_head (I have add_theme_support( 'title-tag' ) in functions.php). I'd like to change the page title format for category archives - currently these look like <Category name> Archives - <Site name> I'd like them just to be: <Category name> - <Site name> Is there a way of achieving this?
If you're using the Yoast SEO plugin (which it looks like you are) then this answer might help you > If you are using yoast SEO plugin then the easiest method is to remove the archive word from "titles & metas-> Taxonomies->category" > > find: > > %%term_title%% Archives %%page%% %%sep%% %%sitename%% replace it with: > > %%term_title%% %%page%% %%sep%% %%sitename%% Alternatively you could try changing it using the `get_the_archive_title` filter as explained here > > add_filter( 'get_the_archive_title', function ($title) { > > if ( is_category() ) { > > $title = single_cat_title( '', false ); > > } elseif ( is_tag() ) { > > $title = single_tag_title( '', false ); > > } elseif ( is_author() ) { > > $title = '<span class="vcard">' . get_the_author() . '</span>' ; > > } > > return $title; > > }); >
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "title, wp head" }