INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Adding custom fields to the header.php I want to add advanced custom fields/custom fields to my header.php as it contains text and phone numbers that we may change - I have tried referencing them but it didn't work. I have also Googled and not found a solution yet. I want to be able to edit the content of the fields from my home page, so I am thinking that might be what I am doing wrong? When I reference the advanced custom fields at the top of my header page in Adobe brackets, the colour of the code doesn't change so I am guessing it isn't allowed there. Would I set something up in functions.php ? EDIT: Adding code example - I have a few fields to add but obvs just need to get one right. As I mentioned, cannot add ref to ACF in the file as you normally do, it doesn't work the same. <div class="pull-right hidden-sm"> <h3>Recruitment: <a href="tel:<?php echo $recruitment_number_ctc; ?>"><?php echo $recruitment; ?></a></h3>
Can you put the following code for displaying content of custom filed? <?php the_field('filed_name'); ?>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "advanced custom fields, custom header" }
Get attachment from post I would like to get the attachment from a post. I want to display a button below each of my post with a link to download them. They will be PDF. How can I do that ? Thank you
You can use ACF(Advance Custom Filed) for this please read document for this > <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "attachments" }
Is it good practice to remove redundant plugins and themes? Is it good practice to remove all of the plugins and themes that are redundant? Also, if so, why is it good practise to remove them?
Always remove any code you do not use which is easy to remove, like unused plugins and themes. Too many times even an unused code proved to be a vector through which sites were hacked.
stackexchange-wordpress
{ "answer_score": 10, "question_score": 3, "tags": "plugins, themes, maintenance" }
What hook should I use that will fire whenever I open a post for editing in the WP back-end? I'd like to create a simple action hook that fires whenever I open a post for editing in the WordPress back-end. What hook(s) can/should I use for this? The action would just be a simple echo command that prints text to the screen (as this is only for testing purposes). Thanks.
Don't what you want to do but here is something that I did earlier on editor page of post type. function wpb_change_title_text( $title ){ $screen = get_current_screen(); if ( 'post' == $screen->post_type ) { //Specify post type $title = 'New Placeholder text will come here '; //Enter new placeholder text } return $title; } add_filter( 'enter_title_here', 'wpb_change_title_text' ); This function will change placeholder text of title textbox of any post type, here I am changing text of post (dashboard -> add post).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks" }
Get post format I have loop and template for post if ( have_posts() ) : ?> <div class="container"> <div class="row"> <?php while ( have_posts() ) : the_post();?> <?php get_template_part( 'template-parts/post', get_post_format() );?> <?php endwhile; ?> </div> </div> <?php else :?> <?php get_template_part( 'template-parts/content', 'none' );?> <?php endif; ?> and I want to use post format and add special html code for eash post format, so i add to my post template (post.php in template-parts): <?php if ( get_post_format() == 'link' ) : ?> //code here <?php endif;?> but it doesnt work. So is it possible to use get_post_format() function in post template file? Or how to check current post format inside post template file?
If you're outside the loop, pass a post ID. $format = get_post_format( $post_id ); To guard against missing formats, add a default to your template: $format = get_post_format() ? : 'standard'; Then you can use your same IF statement: if ( $format == 'link' ) :
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, posts, functions, loop" }
category hierarchy level as a body class - parent cat =1, child cat=2, grandchild=3 I'm finding this next to impossible to find any info on. I'm looking for a way to assign each category level a number and then add that number to the body class. e.g. the parent category archive would show the class `.catlevel-1`, whereas the child category archive would show class `.catlevel-2` ... and so on.
You can achieve this by using the following custom code. You can use the code by adding it in the functions.php file of child theme or in the custom plugin file. add_filter( 'body_class', 'custom_cat_archiev_class' ); function custom_cat_archiev_class( $classes ) { if ( is_category() ) { $cat = get_queried_object(); $ancestors = get_ancestors( $cat->term_id, 'category', 'taxonomy' ); $classes[] = 'catlevel-' . ( count( $ancestors ) + 1 ); } return $classes; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "categories, body class" }
Custom Post Type + Categories I've installed Custom Post Type UI plugin on my client's site. I have registered two new post types called Resources and Case Studies. I've enabled them to have categories and tags support. All of this works fine. However, I want to be able to show a list of categories for only the case studies in the case studies sidebar and a list of the categories for the resource posts in the resources sidebar. Right now they appear to overlap and share categories and tags. Is there something I am missing? If you view this page you will see the sidebar shows < case studies as an option when this is a resource post. Similarly case study posts have a link to resources. I want the categories to be separate and only show on the pages in their hierarchy.
You should use not the categories, but two different custom taxonomies (it's like custom categories, if you're not familiar with with WordPress taxonomies). You can create two separate taxonomies via Custom Post Type UI plugin. screenshot And select to which of the post types, created taxonomy belongs. Also select that custom taxonomy is hierarchical, so it's displayed like a category , not like tags.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, plugins, categories" }
Show stuff everywhere except single post? I was trying to add stuff on my header everywhere except single post using (!(is_single) but it doesnt work. <?php if(!(is_single) ){?> <meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/images/image.png"/> <?php }?>
The is_single is WordPress function so you should add parentheses after it as displayed in the following correct code. <?php if ( ! is_single() ){ ?> <meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/images/image.png"/> <?php } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "functions, single" }
Regenerate thumbnails for images that are not in the media library I have a wordpress site that has thousands of images in the uploads folder that are connected to posts in a custom post type. What would be a good way to regenerate these images to create new thumbnails?
wp-content/uploads images wont regenerate if they are not shown in the Media Library because those media ID's needs to be there in the database.You need to first add your images on the media libray with the help of add-from-server plugin. Then with regenerate-thumbnails plugin you can then regenerate all of you images. Hope that helps!!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "thumbnails" }
Unable to load WordPress local site after changing WordPress Address (URL) and Site Address (URL) I have setup WordPress in my local machine and worked fine. I have accidentally changed WordPress Address (URL) and Site Address (URL). Now I am unable to access the local site. How can I fix this issue? Thank you in advance.
I was able to add WordPress Address (URL) and Site Address (URL) manually and access the local site again. What I did was add following code segments to following files. 1. wp-config.php define('WP_HOME',' define('WP_SITEURL',' 2. Functions.php I have added following code just after opening of update_option('siteurl', ' ); update_option('home', ' ); After that I have refresh site and it worked fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "site url, home url" }
Override template file i subfolders What is the correct way to override theme template files in subfolders with a child theme? I wan't to override a theme template file with the following path: /components/theme-header/ Do I have to create the same path in the child theme or just place the overriding template file with the same name in the root of the child theme?
the child theme should have the file to override the parent theme in the same location. So yes in the same sub-folder location.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, themes, templates, child theme, template hierarchy" }
check_admin_referer not working in custom meta box for custom post type In my callback function (the one which output HTML for forms) of `add_meta_box`, I am using wp_nonce_field( 'uniqueid', 'my_nonce' ) Now in saving function, I am using this at top to verify nonce check_admin_referer( 'uniqueid', 'my_nonce' ) But due to this, I am getting below error as soon as I hit the `Add New` button `Are you sure you want to do this?` (Its 403 default error message ) For now I am using `wp_verify_nonce`, but I don't understand why above code is not working? _Note: I am adding this meta box to a custom post type_
> Now in saving function ... in which hook ? if you do this in "save_post_CPT", it doesn't work because this hook is called a first time a the object creation then you have to do this : add_action("save_post_CPT", function ($object_ID, \WP_Post $object, $update) { if (!$update) { // new object, here you can define default values return; } if (isset($_REQUEST["uniqueid"])) { check_admin_referer( "uniqueid" , "my_nonce" ); // saving informations of the metabox } // here the code when the object is put in the trash or with quick edit e.g. }, 10, 3);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, metabox, security, nonce" }
How are both HTTP and HTTPS versions displaying? We have a site that somehow has both http and https versions accessible. We want to force it all to https. When we try to set the WordPress and Site URLS to https the site ends up in a redirect loop. Using Really Simple SSL doesn't really help as we still end up with a redirect loop. Redirection plugin isn't doing anything that would cause this. I didn't even know you could get a WordPress site to display both versions, let alone how one would go about changing this. Googling/searching Stack exchange for this is rather difficult for obvious reasons, so I apologize if this has been answered somewhere else. Has anyone seen this issue before?
If you can access the SSL version of your blog without a problem, then it means you can redirect all your traffic to it. To do so, take these 2 steps: 1. Access your database using PhpMyAdmin or any other software you want. Head over to `wp_options` table, and change to values of `siteurl` and `homeurl` to SSL version of your blog (for example ` 2. Using any FTP software open and edit your `.htaccess` file the following way: This will redirect all traffics to the secure version of your blog. <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{ENV:HTTPS} !=on RewriteRule ^.*$ [R,L] #BEGIN WordPress RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> Remember not to remove the original rules created by WordPress (the lines below #BEGIN WordPress)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "loop, redirect, https, http" }
Problem with positioning of the menu in custom WP style I have created a style with fully functional menu in the header. The header ends with the border-bottom. When I add following lines to style.css to change the menu appearance: .site-nav ul li { list-style: none; float: left; } then the menu changes its position below the border-bottom of the header. ![enter image description here]( I do not understand, I follow strictly the guide on ` Thank you.
Try using display instead of float: .site-nav ul li { list-style: none; display: inline; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, css" }
Do shortcode in template file I have a fairly complicated shortcode that works well when put inside the wysiwyg editor. Now I try to include this in a template PHP file using `do_shortcode` but it doesn't work. My used but not working PHP source code is: <?php echo do_shortcode('[gfchartsreports include="28" type="bar" chart_js_options="title: {display: true, text: 'Titletext', fontSize:12,fontFamily:'Arial',fontColor:"#000",fontStyle:"bold",padding:20}" custom_search_criteria='{"status":"active","field_filters":{"0":{"key":"created_by","value":"current"}}}']'); ?> I'm not a PHP pro and so I guess the error will be a beginner's mistake. Could anyone help me out with his coding wisdom? Thank's a lot for your help!
I think you need to escape the quotes: <?php echo do_shortcode('[gfchartsreports include="28" type="bar" chart_js_options="title: {display: true, text: \'Titletext\', fontSize:12,fontFamily:\'Arial\',fontColor:"#000",fontStyle:"bold",padding:20}" custom_search_criteria=\'{"status":"active","field_filters":{"0":{"key":"created_by","value":"current"}}}\']'); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, archive template" }
Adding https to wordpress website I am using Cloudflare (service that gives free HTTPS for your website) to have https on my Wordpress website but when I change the site URL and Wordpress URL to ` I get a _"redirected you too many times"_ error. I also tried to add `define('FORCE_SSL_ADMIN', true);` in the `wp-config.php` file and guess what? The same thing happens again. I'm not sure what I am doing wrong but your help would be greatly appreciated... I tried this solution but it doesn't work but returns a 500 internal server error instead.
I have recently solved my issue, I went on wordpress support, found my issue and how to fix it. I installed the SSL Insecure Content Fixer plugin and chose in the plugin settings for SSL Detection, the setting that was recommended. Then, I went to the settings and set my Wordpress and site URL to This all together fixes the infinite redirect loop.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "ssl, https, cloudflare" }
How to change meta data(title, description) for current post? I have a hook, that detects opening the post(publication): add_action('the_post', 'post_callback'); function post_callback($post) { $post->post_title = "New title"; $post->post_content = "New content"; } It replaces `post_title, $post->post_content` data on the custom values. How to change HTML meta data on the page(title, description) inside function: `post_callback`?
Try this: New title add_filter('wp_title', 'filter_posttitle'); function filter_posttitle($title) { $title = 'New title '.$title; return $title; } and new content add code in header.php <?php if ( is_single() ) { ?> <meta name="description" content="" /> <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development" }
How to list Category list in ACF Pro's Select Field to choose from As the title says I want Advanced Custom Fields Plugin to create a Select field which populated with current categories on the site. The exact use case is that the admin can select one category from the list of categories showed on a Select. Then based on that selected category, most 5 recent posts from that category shows on the home page of the site. But this question is only specific to the First Step; Show site's categories in Select Field dynamically. Many thanks.
Set the "Return Value" of the taxonomy to Term ID. This will return the term/category id so that when you get the ACF taxonomy value by using get_field, it will return the id of your category. Then by using following code you can show your 5 latest publish post under that category. $cat_id = get_field('<your ACF field name>'); $args = array( 'post_type' => 'post', //or your postype 'post_status' => 'publish', 'posts_per_page' => 5, 'cat' => cat_id ); $query = new WP_Query( $args ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); the_title(); the_excerpt(); endwhile; endif; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, advanced custom fields" }
Is WordPress cache shared for all blogs in a multisite network? When I do a `wp_cache_set( 'some-item', $item, 'my-group' )` on any site of the multisite network, is `some-item` available on other blogs, or does every blog have its own "cache domain"? If cache is local to the current blog only: Is there a simple way to have a shared, network-wide cache? Could not find anything about this in google or WordPress documentation... _For this question let's assume that there is an **object cache plugin** or drop-in is installed. (I know that out of the box the wp_cache_set function only caches data for the duration of the current request)_
It depends. In general object cache (at least the APCu and memcache based) is global, and is global to the whole server, so the question can be rephrased to "Which caching keys are being prefixed/postfixed with unique strings based on the sub-site". The answer, as can be seen in < is that wordpress core adds a prefix to "non global groups", where the global groups IIRC are the user data related groups and the network settings group. So in good object cache implementation, user data and network options cache will be "shared" across all sub-sites while post cache etc will be "locally cached". This leads to the question of what about the non core `my-group`. One option is that you will add (or not) prefixes base on the blog id when calculating the cache key to use, or add the `my-group` as a global group with wp_cache_add_global_groups if you do want to be able to access the same cache info on different sub-sites
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, cache" }
Avoid having infinite loops I am using the following code (< to sync user role between his blogs on a multisite installation. My question is if this approach can lead to an infinite loop? // Sync user role add_action( 'set_user_role', 'sync_user_role', 10, 2 ); function sync_user_role( $user_id, $role ) { $blogs = get_blogs_of_user( $user_id ); $blogs_count = count( $blogs ); if ( $blogs_count > 1 ) { foreach ( $blogs as $blog ) { $user_blog = new WP_User( $user_id, '', $blog->userblog_id ); $user_blog->set_role( $role ); } } }
Yes it will give you infinite loop, because you're calling the `WP_User::set_role` method within the `set_user_role` action that's again fired within the the `WP_User::set_role` method. Not sure what the setup is but you can try to run it only once, with remove_action( current_action(), __FUNCTION__ ); as the first line in your callback, or use another hook. _Update: I just noticed that I miswrote`filter` instead of `action`, but that would have worked the same though ;-) It's now adjusted._
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "multisite, user roles" }
Subdomains With Wordpress I'll create a WP site that will have multiple subdomains. Consider it's like stackexchange.com I'll have wordpress.stackexchange.com, games.sta...., hardware.sta.... etc. * Should I create all subdomains and their folders and install seperate Wordpress'? * Should I use htaccess to redirect? (I'm not sure I can do that easily with this knowledge) * Should I use a plugin like WP-Network (or something else)?
You want a WordPress network aka WP multi site. There is complete documentation on WP Codex. < In Step 3: Installing a Network, select the sub domain option when prompted. If you are converting an existing site, you will get locked into sub folders instead of sub domains. Go with a clean install to avoid this. New sites are created as sub domains and no plugin is required to manage domain names. Each site has its own content, theme, widget options. Users are assigned rights individually for each site or designate a super-admin with access to all. Network administration (super admin) is able to allow themes and plugins across your full network or site-by-site if you wish. For more information, or a guide to the documentation on the Codex, the folks at WPMU have a great new write-up on WordPress networks: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "multisite" }
first paragraph of the_content as meta description I was trying to use the_content as my meta description, however, i noticed that the texts/content is way too many so I'm thinking if it's possible to use the first paragraph only? Here's the code I'm currently using for meta description. <?php global $post; $content = $post->post_content; if(!empty($content)) {?> <meta property="og:description" content="<?php echo strip_tags($content); ?>" /> <?php }?> Btw, The first paragraph of my the_content has a class. f-desc and here's the code I've used to add it. function first_paragraph($content){ return preg_replace('/<p([^>]+)?>/', '<p$1 class="f-desc">', $content, 1); } add_filter('the_content', 'first_paragraph');
You can use `the_excerpt()` instead of the_content Reference link for filter your excerpt : show-first-paragraph Or you can also do this by callback function inside your loop using the function to modify the_content as below: function get_first_paragraph(){ global $post; $str = wpautop( get_the_content() ); $str = substr( $str, 0, strpos( $str, '</p>' ) + 4 ); $str = strip_tags($str, '<a><strong><em>'); return $str; } Hope this helps!!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, the content, excerpt" }
How can I add text to all posts/pages/categories/homepage etc This should be an easy thing but I just can't get it right. I need to add a piece of HTML to every page on my site however the weird theme I'm using doesn't have a header or footer file that every page uses and I don't want to duplicate code. So what I did was add the following to my functions.php file add_filter ('the_content', 'AddTrackingScript'); function AddTrackingScript($content) { $Tracker .= '<script type="text/javascript">....</script>'; $content = $Disclaimer .= $content; return content; } This works on all articles and pages however the text isn't being added to my home page or to the category pages. Is there a different filter I need to use other than the_content? There is a lot more logic in my real function as certain posts in certain categories don't get the added text but I've simplified it here, just in case someone spots a type ;)
Thanks to some outside help the answer was simplistic, I just need to hook into this add_action( 'wp_footer', 'AddTrackingScript' ); and then simply echo it out and it then gets spat out at the end of the page. function AddTrackingScript() { echo '<script type="text/javascript">....</script>'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, content" }
Remove a div with ID from the_content WordPress I was trying to remove a div having some ID from the_content WordPress. I am trying to achieve something like this jQuery( "#some_id" ).remove(); but on server side, I don't have a clue how I can do this on server side within the_content filter hook. add_filter( 'the_content', 'my_the_content_filter', 20 ); function my_the_content_filter( $content ) { $content.find('#some_id').remove(); return $content; }
I had posted same question on Stackoverflow as well, and below answer worked for me. Maybe someone else need this too. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "the content" }
restored old database now some characters have changed? I had some site issues so I had to restore DB from old backup I used phpmy admin.... import function to restore DB Now all of sudden some characters have changed to "? " I have noticed mostly apostrophes changing to question marks. Like here < Any idea how to fix it? I have tried the comment out part They should look like the following after you comment them out: //define('DB_CHARSET', 'utf8'); //define('DB_COLLATE', ''); But it has not been fixed... Please Help
ok! seems to have it fixed only by choosing Character set of the file latin1 while importing backed up database something mentioned by @chris-o here Faulty restore of the database, encoding issue
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "encoding" }
Aligning line made with CSS I've used CSS to create titles with a double line running from the right had side of the title but am struggling to figure out how to get the right hand side of the lines to line up. ![enter image description here]( The CSS I've used looks like this: `span.fancy:after { content: ""; position: absolute; height: 5px; border-bottom: 1px solid #777272; border-top: 1px solid #777272; top: 0; width: 35em; margin-top: .35em; margin-left: 15px; }` The page I'm working on can be found here: <
Not the cleanest or the best way but, you could simply use left:0; and right:0; to make the border 100% of the content, then wrap your text with another tag with position relative, z-index and add background to overlap the border. Here a example: < You can change the padding-right value to modify the spacing you want.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
problem with readme.txt description and youtube video I am the author of the Bitcoin and Altcoin Wallets plugin and I'm facing an issue with my readme.txt file. I would like to show a video and a text description, like other plugins do. I have entered a description in the description section and a youtube video, as you can see in the link above. The video shows just fine in the plugin page, but if you search for the plugin, in the search results list the description is not shown. Instead the youtube URL is shown in its place. My first thought was to see what others do in this situation, but as far as I can tell, I'm doing exactly the same as this and this: First the description paragraph, then the `== Description ==` header, then the YouTube URL. The description text shows correctly in search result summaries for these other plugins. Can someone please tell me what I'm doing wrong? The validator was not of much help as it does not give you a preview of plugin summaries. Thanks
There's a bug in the parser with regards to short descriptions. I've just been fixing them manually for now when I run across them. Regardless of the reason for the error, you get much better results if you ask the plugins team directly instead of posting somewhere else. We have an email address. plugins @ wordpress.org. You can use that to ask the team with admin access, and they can give you real answers. Asking here is unlikely to get a real answer, unless somebody like me happens to stop by and notice the question. As for your plugin, I fixed it manually. See how simple it can be when you go to the source?
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "wordpress.org, readme" }
Update comment meta for all comments of specific post Questions says it pretty much ... Is it possible to change the comment meta for all comments of a specific post? I know it probably works like this: $comments = get_comments( array( 'post_id' => $post->ID, ) ); foreach( $comments as $comment ) { update_comment_meta( $comment->comment_ID, 'accepted', '0' ); } But is there a more elegant approach?
Your approach will be very slow if there are N no of comments. Use following approach for much faster execution. global $wpdb; $sql = ' SELECT GROUP_CONCAT( comment_ID ) AS ids FROM `wp_comments` WHERE comment_post_ID = '.$POST_ID; $ids = $wpdb->get_results($sql, ARRAY_A); if(isset($ids[0]['ids']) && $ids[0]['ids'] != ''){ $wpdb->query(' UPDATE wp_commentmeta SET meta_value = 0 WHERE comment_id IN ('.$ids[0]['ids'].') AND meta_key = "accepted" '); } **P.S** : Haven't tested the code.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, comment meta" }
Change the Page Title of the Archive Page for Portfolio Tags I want to change the title of the archive page to the name of the Tag itself. See screenshot. ![ARCHIVE - to be changed to TITLE OF THE TAG]( This is under the Portfolio Taxonomy. Please help.
I managed to resolve my question. by just adding this code to the title function of my theme. I didn't know it was not included that's why. } elseif (is_tax() ) { $title = single_term_title( '', false );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, tags, archives, custom post type archives" }
Problem with float:left - unexpected behavior Here you can see the problem with floating:left in my page. I have made a style for wordpress, where I have links to pages and children pages. The links "PC a internet, Grafika, Programování" should be on the same line (right figure). I have added "float:left" to the style.css and the menu is OK, but unfortunately the Title "PC a internet" has moved one row upward (see the right figure). I don't want to have it there. ![Problem with CSS style]( The use of float is probably little bit tricky, could somebody give me advice how to correct it? Thank you.
Add `clear:both;` to your title. example: < **edit:** the code is behaving as it should, floated elements will make the sibling elements that has no clear property align to the side of the floated elements. Setting `clear:both` to your title, stops the floating behavior. You could also use `clear:left` and it'd work perfectly in this case. This is a brief explanation, you could check this link for more detail about clear/float property with examples: CSS Layout - float and clear
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "menus, css" }
remove enclosure url from feed I searched the whole internet, including this website, but there is no written way on how to remove the enclosure url from the WordPress feed. I want to remove it because FeedBurner is adding the image url directly in the email that it is sending to subscribers. The reason doesn't really matter I guess, so simply how to remove enclosure url from the feed? <enclosure url=" length="5873907" type="image/jpeg"/> the feed also has this line, which I also want to remove: <media:content url=" width="7360" height="4912" medium="image" type="image/jpeg"/> any idea on how to do this? everything I tried until now failed, including some answers on this website
You can look if your posts have any assigned `enclosure` meta keys, that could trigger the `rss_enclosure()` core function to print the `<enclosure>` tag. Otherwise you can try this demo plugin: <?php /** Plugin Name: Remove RSS Enclosure **/ add_filter( 'rss_enclosure', '__return_empty_string' ); It looks like you've a plugin that's adding the `<media:content>` tag, e.g. via the `rss2_item` hook. So check your plugins. Otherwise you can try this demo plugin to remove all extra rss2 items: <?php /** Plugin Name: Remove All Extra rss2 Items **/ add_action( 'rss2_head', function() { remove_all_actions( 'rss2_item' ); } ); We can do similar for _atom_ \- and _rss_ feeds. Remember to request the feed with an _url cache buster_ when debugging.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, feed, feedburner" }
Index.php using 100% CPU I am using godaddy 32 gb(RAM), quad core(CPU) dedicated server. My site is working properly till today somehow its take to long to load so i am monitoring server in SSH using top command and i had found that my wordpress `index.php` is continuously requesting. I can see that there are 8-10 request of `index.php` which are in running stat every request runs till 3-4 second and after that a new request is come. I had not added any additional htaccess code. I had deactivated all the plugins but its doesn't work. I am very afraid, is this any attack from bots or something? How to solve this kind of problem? Please let me know if anyone have idea about it. Thanks.
Unless otherwise specified (usually happens on admin side, and image access), all requests to wordpress pass and are processed by the `index.php` file, therefor it is not very interesting to look at which file is being "run", you should look more at the request log and how much time it takes to complete each request. So if it is not any kind of attack, you probably have a traffic spike which might be worth investigating it source, but whether it is a DDOS attempt or just normal traffic, it sounds like either your theme code can be optimized or there is some thing that can be improved in your server setup.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, ssh" }
Template part vs Sidebar (differences) I want to add a hard coded footer into the... `footer.php` of my site. This doesn't need to be "dynamic" (adding and removing widgets), it will be something standard like info about the site and specific links. If I am correct this can be done either by `get_template_part( 'template-parts/', 'infofooter' );` or by `get_sidebar( 'infofooter' );` In the second case I just have to name my file `sidebar-infofooter.php` Are both methods equally valid? What is the difference between a (non-dynamic) sidebar and a template part? Is it that a sidebar usually includes widgets?
The `get_sidebar($name);` function loads sidebar template file `sidebar-{$name}.php` if no name in the prentacies is specified it loads the `sidebar.php` file. `get_sidebar()` and `get_template_part()` are almost identical, at the end they call `locate_template()` function that take care of loading from files. The only difference is the hook fired. If you use `get_sidebar()` for all your widget areas you can target them all later with `get_sidebar` hook if needed. So both options are equally valid in terms of code. They differ in semantics as sidebar usually contains a `dynamic_sidebar()` area inside the template.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "sidebar, footer, get template part" }
How to use wp_query in different column in single loop This is my html structure. i want to display main page in left column which is column 6 and right and side 3 - 3 column which is same category and link with left page. i made page link relation with afc plugins so how can i display main page with link pages in single loop. volunteering We have placed hundreds of international volunteers from 17 to 76 years old from all over the world. [![ summer program - 2 weeks summer program - 3 weeks summer program - 3 weeks summer program - 2 weeks < this is layout.
If you want to display the first post from the loop using a different HTML than the rest of posts in the loop just use a if/else statement. $post_count = 0; if ( have_posts() ) { /* Start the Loop */ while ( have_posts() ) { the_post(); if ($post_count == 0) { // Display 6-wide column // This will be executed just once for first post. $post_count ++; } else { // Display 3-wide posts } } } else { // No posts } Is that the problem you encountered or did you mean something else?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query" }
Add a filter inside an action init Hello in the `init` action, I would like to add a filter to a fairly large function to modify variables in the `$vars` array, for example the Wordpress post ID. That is to say: add_action( 'init',function(){ //code add_filter( 'query_vars',function($vars){ $vars[] = array('ID' => $myid); return $vars; }); }); Is this possible? EDIT: I am doing A/B/C tests of pages and with the same url I want to show a page with another ID, (i.e. edit the ID of the current post to display the complete content of another post).
To alter the page ID before the query is run, hook the `request` filter. If you're using pretty permalinks, `pagename` will be set, you can overwrite `pagename` with another page slug: function wpd_265903_request( $request ) { if( isset( $request['pagename'] ) ){ // any page $request['pagename'] = 'some-other-slug'; } return $request; } add_filter('request', 'wpd_265903_request'); or you can unset pagename and set `page_id`: function wpd_265903_request( $request ) { if( isset( $request['pagename'] ) ){ unset( $request['pagename'] ); $request['page_id'] = 106; } return $request; } add_filter( 'request', 'wpd_265903_request' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "filters, actions, init" }
Localhost WordPress not recognizing my online WordPress account I just downloaded and installed XAMPP and WordPress to be able to create and edit my websites in my local machine, but I have a problem. In the WordPress installation process I was requested to create a new account, so I did. The thing is I already have a WordPress account. The newer one that I created, I did with the same email than this one. I don't want to use the new account, I want to use my previous one to continue to work on the sites I've already created but when I try to log in at localhost it doesn't recognize it. The only one it recognizes is the one that I created in the installation process. How can I log in WordPress at localhost with my previous account?
WordPress do not work like Facebook or Twitter. Each WordPress installation is a separate application, it has its own database where users are stored, each installation is independent of one another. Your localhost installation of WordPres has no connection to the one on the server they are two entirely different entities. But you can copy all contents from your server to your local installation, it is called migration. Here is a very in-depth guide on how you can do that: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "localhost, xampp, sync" }
Reseting file permissions I am having trouble with file permissions on my WordPress site and I found a blog post that suggests to reset them with the following commands: find /path/to/site/ -type f -exec chmod 664 {} \; find /path/to/site/ -type d -exec chmod 775 {} \; However, I am not sure with what I should replace "/path/to/site/". Can someone help?
In this context `/path/to/site` means the absolute path to the root of the content directory of the website. You can find this by navigating to the directory where you installed wordpress and running the command `pwd` (assuming you are on linux). That will output the path you are looking for. By default in many linux/apache installations, this path is `/var/www/html`. If you do not know where wordpress was installed, the process is slightly more involved. Still assuming your server is an Linux server running Apache, to find the "`/path/to/site/`" you can run the command `apachetl -S` (on Debian/Ubuntu) or the command `httpd -S` (on Redhat/Centos). That will output a block that will include a path to a config file. Open the config file and find the line that starts <Directory... The path in the quotes after the word `Directory` is the path you are looking for.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permissions" }
Get the top level comment ID How do I get the ID of the top level comment, as in, the **top parent** comment? Useful functions like `get_ancestors()` and `get_post_ancestors()` don't work with comments.
Wait? Did you just state `get_comment_ancestors()` does **not** exist? What were they thinking... We can do this by looping through the entire comment thread until we find the top level comment. We identify it by `parent_comment` being set to `0`: /** * Return the top parent comment ID * * @param $comment_id * @return comment id */ function cc_get_top_level_comment_id_wpse_265978($comment_id){ if (!is_numeric($comment_id)) return; $parent_comment_id = 1; // loop comment thread until we find the one which has parent comment ID set to 0 while($parent_comment_id > 0) { $comment = get_comment($comment_id); $comment_current_id = $comment->comment_ID; $parent_comment_id = $comment->comment_parent; $comment_id = $parent_comment_id; } return $comment_current_id; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments" }
Display posts on parent post if author coincides On a website, I have 4 _article authors_. I want to display each author's posts on his own _custom post page_. I have come up with this piece of code: <ul class="author-posts"> <?php $catquery = new WP_Query( 'cat=7&posts_per_page=30&order=DESC&author_name=john' ); while($catquery->have_posts()) : $catquery->the_post(); ?> <li class="author-post"><?php the_content();?></li> <?php endwhile;?> The problem with the code above is that only one author's name is **john**. So the WP_Query does not display **terry's** posts. If every parent page (actually, a _custom post_ ) has an author, how do I store the parent page's author in a variable so that I can show on it only the posts belonging to the _current author_? Thank you!
I found it (easy one): In functions.php: // Allow author for custom post function allowShowAuthor() { add_post_type_support( 'cust_post-type', 'author' ); } add_action('init','allowShowAuthor'); In the content _template_ : <ul class="author-posts"> <?php $current_page_author = get_the_author(); $catquery = new WP_Query( 'cat=7&posts_per_page=30&order=DESC&author_name=' . $current_page_author ); while($catquery->have_posts()) : $catquery->the_post(); ?> <li class="author-post"><?php the_content();?></li> <?php endwhile;?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp query, author" }
My title is showing after the shortcode My code is like following: <?php function shortcode_callback() { ob_start(); //my code here ob_get_clean(); } add_shortcode('shortcode', 'shortcode_callback'); ?> The above shortcode add to the page but the tile is showing at the bottom of the shortcode: # My Title > [shortcode] There is anything wrong doing I am.
You needs to change buffer like this: <?php function shortcode_callback() { ob_start(); //my code here return ob_get_clean(); } add_shortcode('shortcode', 'shortcode_callback'); ?> Please check after replace ob_get_clean(); in your code with return ob_get_clean(); then it's working fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, functions, shortcode" }
Recent Posts widget without Title I want to add "Recent Posts" widget in a sidebar without a title but every time I add it, it shows "Recent Posts" text as title. How do I have it without title? I don't want to use any plugin for this. Thank You.
This code will set the title to an empty string if it is set to `Recent Posts` (Which as you noted, is what the Recent Posts widget will set the title to if it is empty): add_filter( 'widget_title', 'wpse_widget_title', 10, 3 ); function wpse_widget_title( $title, $instance, $id_base ) { if ( 'recent-posts' === $id_base && __( 'Recent Posts', 'text_domain' ) === $title ) { $title = ''; } return $title; } Another workaround is to set the title to the HTML entity for a space, `&nbsp;` in the widget editor.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "widgets, recent posts" }
Load custom css in functions.php causing library issue I'm loading custom css stylesheet in my child theme 'functions.php' using this code if (ICL_LANGUAGE_CODE == 'ar') { ?> <link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri() . '/css/rtl.css' ?>" type="text/css"> When doing so, the media library can't be loaded, it just stick like this image: ![enter image description here]( Just a loading spinner with no result, even uploading files is corrupted. When removing the code, everything works perfectly. Any ideas? * * *
If you are echoing this code straight from `functions.php` it would output way before anything else. It is too early in the load process. In most cases enqueue API functions should be used to output assets. Outside of that it is impossible to guess what precisely might it be breaking and how. Examining browser console for errors and such might net some information to go on.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, child theme, media library" }
Organising the plugins folder in wordpress I generally like to use a root folder structure to organise my code files. Is there a way that I can organise my Wordpress plugins folder to organise my plugins? I am looking to have two folders, contrib and custom; * **_custom_** having all the custom plugins that I have written * **_contrib_** having all the contributed plugins which either I have purchased or downloaded from the community. It seems you can move the whole plugin directory, but not really alter the structure within. Does anyone have an idea of how to achieve that? Currently I am just prefixing my custom plugins so that they come up together in a directory view.
WordPress has quite narrow expectation for plugin directory structure. It is tightly coupled with loading process and API functions. While I know attempts have been made to make it more flexible, I am not aware of any real breakthroughs or mainstream adoption. As of current state of core I would estimate you would waste more time trying to implement it, than save time benefiting from more elaborate folder structure. Personally I make any “groups” of plugins or theme and plugins on IDE projects level. For trivia _themes_ on other hand are much more flexible in this regard and core allows to register arbitrary additional directories containing them.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "plugins, customization, directory" }
Home link in the homepage of my wordpress does not show my blog posts I want the home link at the top of my theme in word press to display all the posts i have written so far but when clicking on it the page shows nothing. I have already tried changing the settings as in: Going to **_Settings_** , then inside **_Readings_** , I had **Front page displays** as **A static page** and within it I chose **Home** as **Front page** but even then i get no desired result. I can only display all my posts on my website, when i click on my homepage address lets say www.queries999.com but when i go to www.queries999.com/home, it shows a blank page. Thanks
In _Settings -> Reading -> Front page displays_ select **Your latest posts**. Go to _Appearance -> Menus_. You'll see as the first item **Home** , which points to the physical page 'Home'. Remove **Home** item from the menu. Expand _Custom Links_. Enter **/** ( right slash ) into _URL_ field. Enter **Home** into _Link Text_ field. Click on _Add to Menu_ button. Drag your **Home** to the top of the menu. Save it. Now delete your physical page 'Home'. **Update** : If you don't have a menu defined, yet, you'll have to create one. Go to _Appearance -> Menus_. Click on `create a new menu`link. Enter your desired menu name in _Menu Name_ field and click on _Create Menu_ button. First add your **Home** custom link as explained before. Continue adding other menu items. When done, select **Primary** checkbox in _Display location_ group. Click on _Save Menu_ button. All done.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "frontpage" }
How to restrict type/size of file uploads in any plugin? I have a plugin, in this case it's Woocommerce Product Add-on which has an ability to allow folks to upload a file for the item being purchased. However, there is no restriction and I'm looking for a way to restrict. Since all plugins are handled by Wordpress natively, how can I utilize the `wp_handle_upload(`) and `wp_max_upload_size()` fuctions to control/restrict file uploads? I would very much like some direction please!
You use upload_mimes filter to restrict the image type as : add_filter('upload_mimes','restict_image_type'); function restict_image_type($mimes) { $mimes = array( 'jpg|jpeg|jpe' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', ); return $mimes; } For upload limit you can set in .htaccess one of the following; LimitRequestBody 1048576 //( 1MB) php_value upload_max_filesize 1M php_value post_max_size 1M
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, limit, uploads" }
How to loop through ALL pages? Is it possible to loop through all the pages in a website? If so, how? I'm building a one-pager resume website, and I want to display all of the website's pages as parts of my main page.
I was able to learn how to do it. Here's a solution: $pages = get_pages(); foreach($pages as $page) { echo($page->post_content); }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "loop, pages" }
Insert multiple posts as parent of the first I am trying to create some posts using the `wp_insert_post`. I want all the posts to be parent of the first. I tried different approaches with no luck. Does anyone have any idea how this could be done? foreach ( $books as $book ) { $post = array( 'post_title' => esc_html__( 'Post', 'book-cpt' ), 'post_content' => 'test', 'post_status' => 'publish', 'post_type' => 'book', ); $book_id = wp_insert_post( $post ); };
If I understand you correctly, this should work: $first_post = true; $post_parent = 0; foreach ( $books as $book ) { $post = array( 'post_title' => esc_html__( 'Post', 'book-cpt' ), 'post_content' => 'test', 'post_status' => 'publish', 'post_type' => 'book', 'post_parent' => $post_parent ); $book_id = wp_insert_post( $post ); if ($first_post) { $post_parent = $book_id; $first_post = false; } };
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp insert post" }
Using shortcode in Post title I have lots of posts where I have current month with the post title. When month ends, it's kind of annoying to change all the posts manually. So, I created a shortcode to show the current month. I used _`add_filter( 'the_title', 'do_shortcode' );`_ to execute the shortcode in title. It all works fine. Problem is, in the meta title, the raw shortcode is showing instead of the output. Any suggestions how I can work it out. Thanks in advance.
The filter for the title is `single_post_title`, you can do the same thing you do with `the_title`: add_filter( 'single_post_title', 'do_shortcode' );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "shortcode" }
Creating interactive drop down lists in a post I am writing a blog post and in that blog post i want to have a drop down list which contains all the football teams and upon selecting a specific team in that drop down box would lead to a change in second drop down list or box which would contain the players names. How could i do this in word press especially without the use of coding. Any pointers very much appreciated. Thanks
Unfortunately unless there's a plugin you can't do this custom code (javascript) on wordpress.com - see "Javascript" section on this page. You could do this on a self-hosted wordpress.org site using a plugin like this: Ajax Dropdowns You might be able to use a form builder and then iframe it in to your page like Wufoo: < but again this code can't have any javascript.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts" }
How to get current page id through the plugin This is my code. /* Plugin Name: Plugin URI: Description: Version: Author: Author URI: License: License URI: Text Domain: Domain Path: */ if ( ! defined( 'ABSPATH' ) ) { exit; } $page_object = get_queried_object(); var_dump($page_object); $page_id = get_queried_object_id(); echo $page_id; I am geting >> Fatal error: Call to a member function get_queried_object() on a non-object in C:\wamp\www\wordpress\wp-includes\query.php on line 45
Take a look at the Plugin API/Action Reference, particularly the section _Actions Run During a Typical Request_. In WordPress, you're going to want to hook your code to various specific points of execution, otherwise it will be executed immediately, which is often not the desired result. The code you posted is going to be executed as soon as the plugin is loaded, which takes place on the `plugins_loaded` hook. That's way too early in the flow of loading a page (for example) to be getting a post/page ID. Below, I've wrapped your code in a function that is hooked to the `template_redirect` hook and now it generates the expected results. add_action( 'template_redirect', 'wpse_inspect_page_id' ); function wpse_inspect_page_id() { $page_object = get_queried_object(); var_dump($page_object); $page_id = get_queried_object_id(); echo $page_id; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugin development" }
Why content is not adding for each blog post my posts Cant find all blogs.The wordpress see only home <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h2><?php the_title(); ?></h2> <?php the_content(); ?> <?php endwhile; else : echo '<p>No content found</p>'; endif; ?> But there it working stable <
Odds are you have assigned a Static Front Page under `Settings -> Reading`. Whenever you assign a static page as your front-page, WordPress will display that page's content instead of your blog posts. You can assign a separate page as your "Posts Page" which, when displayed, will display your blog posts. You can either assign a Posts Page or change the setting to display your latest posts. For more information you may read: What is: Static Front Page by Syed Balkhi at WPBeginner
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, loop" }
Problem with submenu position when nav bar is at the bottom I'm using twenty seventeen theme on wordpress (writing a child theme) When the home page first loads the nav bar is at the bottom of the screen, but the sub menu opens downwards and is therefore hidden. I'd like it to fly upwards until the page has scrolled down. First, is there a simple way to change this that I'm perhaps missing? (because it seems like a basic thing, yet I can't find any answer anywhere) Or do I need to change a class on scroll using jquery? (in which case I am really feeling about in the dark.) Can anyone help me with this? Vik
The easiest way would be to react to the change of classes assigned to the main menu bar - when it docks top - there's added class `.site-navigation-fixed`. Making it work fully is not so quick and easy process, especially when you do the edits in the Chrome developer tools :) You have to take care of the RWD version too. I made some changes for you for a start: @media screen and (min-width: 48em) { .navigation-top.site-navigation-fixed ul li:hover > ul, .navigation-top.site-navigation-fixed ul li.focus > ul { top: 100px; } } @media screen and (min-width: 48em) { .main-navigation ul li:hover > ul, .main-navigation ul li.focus > ul { left: -6.5em; right: auto; top: -100px; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme twenty seventeen" }
What's the best way to add taxonomy's image in 2017? Need to build image upload for custom taxonomies. I used `Categories Images` plugin before, but now I need 2 images and this plugin doesn't fit anymore. I'm looking for a best solution. Does anybody knows it in 2017?
Here is something I use generally.. Please refer this link . and follow. This will help you definitel thanks
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, custom field, uploads, media library, media modal" }
AMP - Change rel="canonical" from functions.php the source action in > /amp/includes/amp-post-template-actions.php is: add_action( 'amp_post_template_head', 'amp_post_template_add_canonical' ); function amp_post_template_add_canonical( $amp_template ) { ?> <link rel="canonical" href="<?php echo esc_url( $amp_template->get( 'canonical_url' ) ); ?>" /> <?php } How I can edit rel from functions.php without editing main file? thanks.
In general you can deregister the action's callback, after it's been registered and then register your own before it's invoked with `do_action( '...' )`. Here's an example: // Add your own with later priority, e.g. 11 or wrap it in another later hook: add_action( 'amp_post_template_head', 'wpse_amp_post_template_add_canonical', 11 ); function wpse_amp_post_template_add_canonical( $amp_template ) { // Remove the unwanted callback: remove_action( 'amp_post_template_head', 'amp_post_template_add_canonical' ); // Modify this new output to your needs: printf( '<link rel="canonical" href="%s" />', esc_url( $amp_template->get( 'canonical_url' ) ) ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, actions" }
Wordpress wp_mail() how to add a .GIF I'm using wp_mail() to send e-mail from our website. However, we would like to include a .gif file on the body of our message. Here's my code, but it's not working. $to = $contact['Email']; $from = '[email protected]'; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Create email headers $headers .= 'From: Testing Mail <'.$from .'>'. "\r\n"; $subject = "Subject Text"; $customer_name = $contact['FirstName']; $message = '<html><body>'; $message .="<p>message!</p>"; $message .= "<p>message </p>"; $message .= "<img src='img/signature.gif'>"; $message .= '</body></html>'; wp_mail($to, $subject, $message, $headers);
You have to provide the absolute path for your included image, as the receiver of the email does not have a file "signature.gif" in a folder "img" (that's where the client is going to search it) Replace $message .= "<img src='img/signature.gif'>"; with $message .= "<img src=' Where _yourwebsite.com_ is your website's domain followed by the complete path. Depending on where you added your code, you can access a WordPress function, to add the domain dynamically. This is useful if you have to move your website to another domain (for a staging/developing enviroment for example). Have a look at get_site_url()%22). You could use it like this: $message .= "<img src='" . get_site_url() . "/PATH/TO/img/signature.gif'>";
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp mail" }
what is best way to keep track of changes made in wordpress website? I have a website which has many admins. What is the best plugin or any other functions which would do this work? Any suggestion would be a great help. Thank you.
There are many plugins that display the history of changes made by site's users. Personally, I have used Simple History plugin. It is easy to use, have a clear interface and useful log searching capabilities. For the list of similar plugins, you can read this recently updated article on wplift.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, admin, security, plugin recommendation" }
What is the database table for pages? When I go through the database of a fresh Wordpress 4 install I find, for example: wp_posts wp_terms wp_users Yet I didn't find `wp_pages'. Where is it?
the wp_posts include all post types (post, page, custom post..), and to differentiate between them there is a field called post_type used to specify the name of the current entry whether it's a page, post or a custom post. Query below will get list of pages SELECT * FROM wp_posts where post_type = 'page';
stackexchange-wordpress
{ "answer_score": 11, "question_score": 4, "tags": "database" }
how add css class to product boxes li, for img, add cart button, decs, price… please if you could help. I have differect resolution and aspect ratio of images uploaded to product. When i see product list: < products boxes are not same, i would like all images are fit to cell width, need "add to cart" button in same line for all product boxes ...atc all i can manage via css classes, but my problem is how i can add class to that elements inside * tag. Thank you very much.
You don't need to add class to those elements. You can apply CSS style to those elements by using following selectors respectively. .post-type-archive-product ul.products li.product .post-type-archive-product ul.products li img .post-type-archive-product ul.products li .button .post-type-archive-product ul.products li .woocommerce-loop-product__title .post-type-archive-product ul.products li span.woocommerce-Price-amount.amount
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to add local users to wordpress without email password? I want to organize my posts with random names.Each post will have many authors (those are not actual/real authors).So i do not want to give them any email or password to log in. Actually,i am trying to make project lists and each project has many contributers and each contributer can work on many project.i use Co-authors plus plugin to set authors to a post. In the future, i'll show/list all projects which belongs to a specific author in author.php * How can i add/upload profile picture to each user without gravatar? * How can i create those users without email and password (this users are not real.so they won't log in site :p) Can someone give me an advice to achieve this? Thanks.
I had same issue a month ago. As you I tried to use Co-Author Plus, but with the Plugin I haven't reached my goal. So , at the end, I thought that they are not real user and I make them like a custom taxonomy and I solved any problem
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "users, user roles, profiles" }
How to edit a deleted image gallery? Picture this scenario: 1. From the "Add/Edit Post" page in WP, click the Add Media button. 2. Click on "Create a Gallery" on the sidebar and do exactly that. Then insert it into your post. Let's call this gallery "Main Gallery". 3. Save your post. 4. Delete the gallery from the WYSIWYG editor. 5. Save your post again. Is there any way to edit "Main Gallery" once it's not visible from the editor? I know it's not gone. I'm using the code in this post and the gallery is displaying. If I redo steps 1 to 3 again, creating another gallery (let's call it "Secondary Gallery"), the code referenced above does not display "Secondary Gallery", it displays "Main Gallery", so I know it still exists. So is there a way to edit this now-hidden gallery? If not, any pointers as to how I could alter the code above to display only the newest created gallery instead of the oldest?
Wordpress galleries are not true "objects", they are just a kind of one time macro. There is no real DB of them, just a shortcode in the content and once you deleted it, there is no gallery any more (except for in the old revisions). The code you referenced is a relic of the old days in which by default a gallery would have been all the images associated with a post, but those old days are long gone and unless you insert `[gallery]` manually, the current way is to add the ids of the images to the shortcode and once the shortcode is deleted.... puff you can't restore it from any other place except for backup.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "media library, gallery" }
Create an if statement based on page_id I'm creating custom content and I want to show different content based on my page ID. For example, in home page I don't want to show anything but in another page I want to fill that space with some text and in other different page I want to fill the same space but with different text. In my page.php is where I want to put this "IF" statement as follow: IF (is_home) {display nothing } ELSE IF (is_page_id=1111) {display text01} ELSE IF (is_page_id=2222) {display text02} How can I control this using php?
You don't need `if (is_home)` \- the homepage doesn't use `page.php` as a template, and you're checking for page ID anyway, which the homepage shouldn't match. To check what page you're on you can use `is_page()` with the page ID. if(is_page(1111)) { display text 01; } elseif(is_page(2222)) { display text 02; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "php, pages" }
WP_Query attachments by multiple IDs I would like to get 2 images in media by their IDs. If I want to get only one image I would use this code $args = array( 'p' => 1, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'no_found_rows' => true, 'posts_per_page' => 2, 'post_status' => 'any' ); $query = new WP_Query($args); How can I do it for 2 images, without double queries? It would be great if I can pass an array with IDs but `'p'` according to Codex can be only integer 'p' => array(1,2), p (int) - use post id. Default post type is post.
I think you need to use `post__in` . The code will be something like: $args = array( 'post__in' => array( 1, 2 ), 'post_type' => 'attachment', 'post_mime_type' => 'image', 'no_found_rows' => true, 'posts_per_page' => 2, 'post_status' => 'any' ); $query = new WP_Query($args);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp query" }
How can I create custom button in post.php I want to create a custom button to go the customize.php. I want to create it here ![I want to create it here](
Use **media_buttons** action for it. Check below code. add_action('media_buttons', 'add_my_media_button'); function add_my_media_button(){ echo '<a href="'.get_site_url().'/wp-admin/customize.php" class="button button-default">Customize</a>'; } Hope this will helps you. Thanks!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts, customization, publish, buttons" }
Woocommerce table is missing a heading--can I add it by use of a hook? My Woocommerce shopping cart page displays a column for my product thumbnails, but the heading of the column is missing (screenshot). Can I add a heading here by using a filter hook? If so, can anyone suggest the particular hook to use? I've looked through the big book of Woocommerce hooks, but can't seem to find one that pertains to the headings in this table. I am aware that I can complete this task with JavaScript, but for this particular case I would like to use a hook, if possible. Thanks.
I dont know about the particular Hook but, you could do it by simply using CSS like this: th.product-thumbnail::before{ content: 'insert_title_here'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, woocommerce offtopic" }
the_title filter applying to menu items I want to create a simple function to call the logged-in user's username along with the word "Wishlist". It seems to be working but it also changes the menu item titles! function customize_wishlist_title( $title ){ $current_user = wp_get_current_user(); $loggeduser = $current_user->user_login; if ( is_page( 258 ) ) { $title = '<span class="username">'.$loggeduser.'\'s'.'</span>'.'&nbsp;'.'<span>Wishlist</span>'; } return $title; } add_filter('the_title','customize_wishlist_title', 10, 2);
Use `in_the_loop()` conditional tag to make sure you are modifying the title inside the Loop and to prevent the hook changing titles somewhere else: function customize_wishlist_title( $title ){ $current_user = wp_get_current_user(); $loggeduser = $current_user->user_login; // give attention to the following condition: if ( is_page( 258 ) && in_the_loop() ) { $title = '<span class="username">'.$loggeduser.'\'s'.'</span>'.'&nbsp;'.'<span>Wishlist</span>'; } return $title; } add_filter('the_title','customize_wishlist_title', 10, 2); See `in_the_loop()` reference.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 3, "tags": "title" }
Show About and Contact Us page when they're clicked in the top menu. I have a page.php file wich simply looks like this: <?php get_header(); ?> <div class="clear"></div> <div class="clear"></div> <?php get_footer(); ?> On the other hand I have made two pages named About and Contact Us in **my WordPress admin panel** and I've added them to my site's top menu. Now when I add some content to one of these two pages and open it by clicking its name from the top menu the content is not shown. How can I fix this issue? I want to show all of my self-made pages (pages that are made using WordPress admin panel and are different from single.pho, index.php, category.php and search.php) using the page.php layout. How can I do this?
You need to include a loop to retrieve the page content. Something like: <div id="primary" class="site-content"> <div id="content" role="main"> //BELOW HERE <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php comments_template( '', true ); ?> <?php endwhile; // end of the loop. ?> //ABOVE HERE </div><!-- #content --> </div><!-- #primary --> ## More on Page Templates: Possible Tutorial Starting Point And Page Templates from the WP Codex on Page templates: > page.php — If a specialized template that includes the page’s ID is not found, WordPress looks for and uses the theme’s default page template. So if you haven't assigned anything in the admin, and no more specialized templates exist, your page.php file is being called.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, theme development, menus, pages" }
Contact form function should be in functions.php or in a plugin file? I have a function right now in my functions.php file that display a contact form on the frontend, also checks the user data and send an email, so the question is, should I leave this just where it is ( functions.php ) ?? or include it in a plugin. I have to say that until now the mentioned form is attach to the theme functionality, for example it uses the colors selected by the user on the customize screen, but I want to know if in this case belongs to the “plugin territory”, thank you very much!
This depends a lot on the context. Normally, I would say that the form should be in a plugin. The rule of thumbs is that if it's a functionality that could still be needed when the theme is deactivated, then it should go into a plugin. Now for your specific case, if using the customizer, would set options that could potentially break your form if the theme should be changed, then you should keep it in your theme's `functions.php`. But, I would still argue that it should go into a plugin and you should make sure that, in the eventuality that the theme is changed, you set default values to the form to replace the customizer options. Because chances are that even if the theme is changed, you'd still want the contact form to be active.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, theme development" }
customizing a theme I need some information about WordPress theme customization (or) editing could anyone tell me what is the best ways to customize WordPress theme. Thanks :)
This is a very very broad question, probably isn't the place for it tbh. But anyway, there are many many themes in existence already, you can modify them, generally by adding a child theme and making your modifications there, it is bad practice to update a theme directly. If you wish to extend the functionality of your site, then maybe a plugin, custom or not may be a better solution for you. If you wish to add custom post types, meta fields etc, it is advisable to do this outside of the theme core files. Again there are a vast array of plugins out there to extend and modify the look, functionality and usability of practically any type of site! Start here - <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "customization, themes" }
Using HTML links within translatable string What harm could happen if I didn't use the `wp_kses` function when using HTML links within translatable string? I know what this function do but what I don't understand is why and when should I implement this function? Specially with translatable strings.
It basically depends on who is doing the translation and how trusted can he be as if you will not filter things out the translator can add JS code, still cookies and whatever. In most of the places translation is done you will have in any case a call to `esc_html` or `esc_attr` which will mitigate the problem, but obviously if you need an actual link, you can not use those functions. The use of `wp_kses` just makes sure there are no surprises in the translation. For example, there is nothing that prevent a translator from translating `__('Hi there`) into `Hi there <script>alert('evil laugh')</script>`. translations are never verified to not include such type of things when they are submitted by translators, and while the example is easy to catch, it might be possible to do more complex things that are harder to spot.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, theme development, security, translation" }
Edit permalink for certain pages I'm creating a website based on an old and positioned one. I've created all the sections and I need to know how can I add "/services/" as a prefix for some pages... I mean, not all pages are services, so for those that are, I want to add the "services" folder before the page name. It would be something like this in the end: `mysite.com/services/marketing-strategy.` instead of `mysite.com/marketing-strategy.` as it is now. I tried editing the permaking but it removes the slash ( / ) character. Also permalinks configuration applies to ALL pages, and I need this to be only on some of them. What's the best way to do this?
I agree with @Milo it would be easiest to do it by having the Services Page as your top level page (parent) and then declare other pages as the Services pages' children. You can do this on the page editing area in the WP admin area. Try not to mess with the permalinks as that can have crazy consequences on things working as they should. If that solution doesn't work out, create a custom post type of services. That way anything in that custom post type will be under the services type! There are a variety of plugins to help with this. You could also write your own plugin to do this too!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks, pages, urls, links" }
Changing the entire control choices using wp.customize with JavaScript Let's say I have two customizer controls "setting_category" and "setting_font", I'm trying to change the choices of "setting_font" upon changing the value of "setting_category". Here's what I'm doing: ( function( $ ) { var api = wp.customize; api( 'setting_category', function( value ) { value.bind( function( to ) { var newChoices = {}; // get new data from JSON using 'to' and populate the 'newChoices' api( 'setting_font' ).changeTheChoices( newChoices ); } ); } ); } )( jQuery ); How can it be done with JavaScript? Any trick?
Here's the solution that I found, it may be useful for some instance: parent.wp.customize.control( 'setting_category', function( control ) { control.setting.bind( function( to ) { var selectElem = parent.wp.customize.control( 'setting_font' ).container.find( 'select' ); selectElem.empty(); $.each( jsonData['items'], function( key, item ) { if ( item['category'] === to ) { var option = $( '<option></option>' ) .attr( "value", encodeURIComponent( item['family'] ) ) .text( item['family'] ); selectElem.append( option ); } } ); } ); } );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development, ajax, javascript, theme customizer, json" }
How to make wordpress Dynamic Search-Bar from Predesigned Static Html Search-Bar? I am converting my static HTML code into dynamic WordPress theme. In my `header.php` there is already been coded for a Search-Bar which have nice look & feel. Code block looks like this: <div id="search"> <div class="button-search"> <input type="text" placeholder="Search..." onfocus="" /> </div> </div> What if I want to use exactly this search-bar to be converted into dynamic search bar without changing it's CSS. I mean I don't want to use wordpress's default function of Search-Bar (form) `get_search_form()`.
Yes, it's pretty easy to make our static HTML Search-Bar dynamic. _First,_ wrap up our `<input />`tag with `<form> </form>` tag mentioning `action=""` and `mehotd=""` _Second,_ **identify** the default **key** of wordpress and **assign** it in `name=""` attribute of input tag. To be specific, the code would be like this: <form method="GET" action="<?php bloginfo('home'); ?>"> <input name="s"placeholder="Search..." /> <input type="submit" value="Submit"> </form> **How to identify:** we may use `<?php get_search_form(); ?>` in header.php (just for a temporary test) to get the default search-bar of wordpress so that we can search any word in it. Let, we search with a word (post) written in search bar. Then we will get the result with all post words written, if we look at the address bar we are supposed to see like this: your_website.com/?s=new So, **s** & _new_ is the **key** / _value_ pair identified. Hope it helps.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "search" }
CSS ?ver=4.7.3 not found I've moved my website to a cloud service, and after moving files, database, and updating database I get one of theme CSS file not found, and a suffix has been added to it with the WordPress version "?ver=4.7.3". How can I solve that?
If your file working without query string then you can remove the query string by adding the following into functions.php // Remove WP Version From Styles add_filter( 'style_loader_src', 'sdt_remove_ver_css_js', 9999 ); add_filter( 'script_loader_src', 'sdt_remove_ver_css_js', 9999 ); // Function to remove version numbers function sdt_remove_ver_css_js( $src ) { if ( strpos( $src, 'ver=' ) ) $src = remove_query_arg( 'ver', $src ); return $src; } or you can try a plugin which does same. Remove Query Strings From Static Resources
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
whats the mistake → href="get_permalink() <?php echo '<h1><a href="get_permalink()">' . get_the_title() . '</a></h1>'; ?> This is not generating the permalink → href="get_permalink() I also tried this version → <?php echo '<h1><a href="get_permalink()">' ?> <?php . get_the_title() . '</a></h1>'; ?> whats wrong you can get the feel here → Click Here Click on any link it will not take you the desired single page as expected. Please forgive me If you think I am doing a very silly mistake. we all were novice some day before we became a pro.
Try below code. <?php echo '<h1><a href="'.get_the_permalink().'">'.get_the_title().'</a></h1>'; ?> Hope this will helps you. Thanks!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks" }
Pass query string to page I wrote this function in my functions.php function header_resized_img ($path, $width, $height) { $image = wp_get_image_editor($path); if (!is_wp_error($image)) { $image->resize(9999, $height, false); $orig_size = $image->get_size(); $image->crop($orig_size['width']/2-$width/2, $orig_size['height']/2-$height/2, $width, $height); $image->stream( $mime_type = 'image/jpeg'); } } To make it work, i created a file named page-image.php, then a page with permalink < Inside page-image.php i've put (just a test) header_resized_img (get_header_image(), 414, 700); which, in facts, does output the resized/cropped image when i visit it. Now i want to make it more flexible and pass parameters through URL. I tried query strings using `$_GET`, then i found `get_query_arg`, but none of these seems to do the trick. How could i do this? Thank you.
This should actually work for you: function header_resized_img () { $image = wp_get_image_editor($_GET['path']); $height = $_GET['height']; $width = $_GET['width']; if (!is_wp_error($image)) { $image->resize(9999, $height, false); $orig_size = $image->get_size(); $image->crop($orig_size['width']/2-$width/2, $orig_size['height']/2-$height/2, $width, $height); $image->stream( $mime_type = 'image/jpeg'); } } and include your function somewhere in the template: `header_resized_img();` Then try accessing this URL: ` To generate your image.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "query string" }
Getting wp_footer() to work without wp_head() I have an external website that needs to load the header and footer from another site in Wordpress. I've managed to have this done with the following code: <?php require_once("wp-blog-header.php"); /* setup the wordpress environment */ require_once(dirname(__FILE__) . "/includes/head.php"); ?> This code outputs the correct header. Inside `head.php` I call `wp_head();` and all works as excpected. When I do the same thing for the footer, the `wp_footer();` function doesn't output the scripts. It only outputs the scripts if I call `wp_head();` right before `wp_footer();` This works but it also outputs all of the header inside my footer which is not something I want. How can I execute `wp_footer()` without having to call `wp_head()` or how can I just output the scripts that are loaded via `wp_enqueue_script()` in my functions.php page to the footer? Any ideas? Thank you in advance.
For what it's worth, I found a solution to my problem and posting it here for other lost souls :) <?php require_once("wp-blog-header.php"); /* setup the wordpress environment */ // This is to fool the system // In order for wp_footer() to execute, we need to run wp_head() but since we don't want the output of the header again, // we put it in a buffer, execute the function and then clear the buffer resulting in what we need ob_start(); wp_head(); ob_clean(); require_once(dirname(__FILE__) . "/includes/footer.php"); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp enqueue script, headers, footer" }
Admin Order adding an extra product on add_line_item It happens from time to time, i have to add a WC order manunally from my admin panel - but the thing is i want it to automaticly add a certain product, if if certain parameters is set. Let's say im creating a new order, and im adding product ID #646, and since a certain parameter is set on that product, i also want it to add product ID #800. So when pressing the "Add Product" button, as seen below it should add product id #800. I have been trying to find a hook i can use, but i seem unable to find a hook that is fired when pressing the "add Product" from the admin order panel - or anything similar. Am i looking the wrong place? is it even possible? If anybody could point me in the right direction, i would appreciate it!
So i manage to solve the problem myself after looking little more around, the hook is super poorly named. But it does the trick! It fires after the order is created, so you can manipulate the order as you wish. add_action('woocommerce_process_shop_order_meta', woocommerce_process_shop_order', 10, 2); function woocommerce_process_shop_order ($post_id, $post) { global $woocommerce; $oOrder = new WC_Order($post_id); //add product }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to - proper WordPress 301 redirects? I need to 301 redirect: `example.com/service-1.html` to `example.com/our-services/1/`. I've tried redirect plugins and `.htaccess`: 1. `Redirect /service-1.html /our-services/1/` 2. `Redirect 301 /service-1.html 3. `RewriteRule ^service\-1\.html$ /our-services/1/? [L,R=301]` 4. `RewriteRule ^(.*)/service-1.html$ [R=301,L]` But nothing is working, every time I'm redirected to (Woocommerce) product page `product/1`. Wordpress `.htaccess` file: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress What am I doing wrong?
You may be adding the directive to the wrong part of your `.htaccess` file? It needs to go at the top, before the existing WordPress directives. You should also use `RewriteRule` (ie. mod_rewrite) since you have existing mod_rewrite directives (the WP _front controller_ ). Something like your 3rd attempt at the top of your `.htaccess` file should result in the appropriate redirect. For example: RewriteRule ^service-1\.html$ /our-services/1/? [R=302,L] Change to a 301 (if that is the intention) only when you are sure it's working OK. 301s are cached hard by the browser, so you will need to ensure the browser cache is cleared before testing. The `?` on the end of the `RewriteRule` _substitution_ simply removes the query string from the request. Whether this is required or not is up to you, but you don't have a query string in your example.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic, redirect, htaccess" }
How to make an edit to an already published post back to Draft I have a marketplace using WooCommerce where the Vendors have their own set of products. Once they first create a product, an admin needs to approve and publish it for them. The problem is that, once a product have been published, the Vendors can edit it and re-save with different content that very often is different from the approved one. I would like to know how I can make sure that if they edit an already published product, the post goes back to "Submit to Review" or "Draft" status. Thanks!
Add below code in your **current theme's functions.php** file. You have to replace **USER ROLE** with your user role name in if condition. function check_edit_post($post_id){ global $post; if( in_array('USER ROLE', wp_get_current_user()->roles) && 'product' == get_post_type($post_id) && 'publish' == get_post_status($post_id) && $post->post_date != $post->post_modified ){ wp_update_post(array( 'ID' => $post_id, 'post_status' => 'draft' )); } } add_action( 'save_post', 'check_edit_post' ); Hope this will helps you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, permissions" }
Redirect to woocommerce checkout after adding to cart - item already in cart I have this code /* * Redirect to checkout after adding to cart */ function themeprefix_add_to_cart_redirect() { global $woocommerce; $checkout_url = $woocommerce->cart->get_checkout_url(); return $checkout_url; } add_filter('add_to_cart_redirect', 'themeprefix_add_to_cart_redirect'); The problem is clicking on a link like `www.example.com/?add-to-cart=1234` will not trigger the `add_to_cart_redirect` hook if there is something already in the cart. It thinks that there is something already in the cart and there is nothing else to add. _Only one of my products can be purchased at a time._ **Where can I hook in to redirect at an earlier stage in the cart validation process?** or **Is there a way to empty the cart before adding the product`1234`?** Thanks!
**Q: Is there a way to empty the cart before adding the product 1234?** A: Before adding a product to the cart, it is possible to empty the cart so that the `add_to_cart_redirect` hook will always be called. Use the `woocommerce_add_to_cart_validation` hook to alter the cart before adding a new item. /** * First clear the cart of all products */ function clear_cart_before_adding( $cart_item_data ) { global $woocommerce; $woocommerce->cart->empty_cart(); return true; } add_filter( 'woocommerce_add_to_cart_validation', 'clear_cart_before_adding' ); /** * Redirect to checkout after adding to cart */ function themeprefix_add_to_cart_redirect() { global $woocommerce; $checkout_url = $woocommerce->cart->get_checkout_url(); return $checkout_url; } add_filter('add_to_cart_redirect', 'themeprefix_add_to_cart_redirect');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, hooks, woocommerce offtopic" }
Change directory url to be same as page permalink? I have a page with permalink set in the dashboard to `www.domain.com/reports` that has links to PDF reports located in `www.domain.com/wp-content`. There is not a reports directory on the server and creating one in the root directory, obviously breaks the `www.domain.com/reports` page. How can I change the settings and/or file structure such that the PDF links are `www.domain.com/reports/<pdf document>` without overriding or conflicting with the permalink?
I have an idea, let's see if it helps you. You may create separate pages for each pdf file and make Reports page as parent of these pages. Then inside the child pages, you can embed the pdf files with a PDF Reader plugin or simply using an iframe tag. Thanks
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks, url rewriting" }
Remove TEXT EDITOR form page I'm looking for a way to remove text editor from page because i'm using Beaver Builder plugin (for building my pages). like you see in the picture bellow, i have 2 tabs. I want to remove text editor tab (in the red color). Thanks in advance. ![enter image description here](
This question has an answer here . I think this will work for you. Let me know after trying add_action('init', 'init_remove_support',100); function init_remove_support(){ $post_type = 'page'; remove_post_type_support( $post_type, 'editor'); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "html editor" }
get_post_thumbnail does not display thumbnail I'm trying to get a specific post's thumbnail by using the post's ID. I have this code snippet in my index.php file <?php get_the_post_thumbnail(64 , 'post-thumbnail', array( 'class' => 'img-format-big' ) ); ?> It doesn't return any image/thumbnail at all. Anything wrong with the code?
Make sure to use `echo` with `get_the_post_thumbnail()`: echo get_the_post_thumbnail(64 , 'post-thumbnail', array( 'class' => 'img-format-big' ) ); In WordPress, a rule of thumb (no pun intended) is to use `echo` with functions prefixed with `get_`. Functions prefixed with `the_` on the other hand, display their output immediately (e.g. `the_post_thumbnail()` ).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails, thumbnails" }
Updating modified templates I want to tweak some of the .php template files in my WordPress theme, and I understand that the correct process is to copy the relevant files into a child theme folder and edit the files there, so that my modifications won't be lost in future theme updates. But does that mean that I then won't get the benefit of theme updates to the files I've put in my child theme folder? This might not be a good thing, as the theme update may have added some useful features, or even fixed the issues for which I initially needed to make the code tweaks! What's the common solution to this? Someone suggested a Diff app - is this what people commonly use?
Yes, it's about to check changes after updates of main theme, mostly updates goes to core of theme, not files like single.php etc.. but when it's go this way, you need some Diff program. Check this out: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "templates, child theme, updates" }
How to filter to output of the get_permalink() function I know how to filter the output of the function `the_permalink` \- it is like this: add_filter('the_permalink', 'my_the_permalink'); function my_the_permalink($url) { return ' } And it works when I use it like: `<?PHP the_permalink($id); ?>`, but I wanted to change the link returned by `get_permalink($id)` function. And this filter doesn't affect the returned permalink in that case. I was trying to catch it with: add_filter('post_link', 'my_get_permalink', 10, 3); function my_get_permalink($url, $post, $leavename=false) { return ' } But this filter isn't fired for the `get_permalink()`. So how can I alter the links returned by the `get_permalink()`?
Note that `post_link` filter is only for the `post` post type. For other _post types_ these filters are available: * `post_type_link` for _custom post types_ * `page_link` for _page_ * `attachment_link` for _attachment_ The `get_permalink()`function is actually a wrapper for: * `get_post_permalink()` * `get_attachement_link()` * `get_page_link()` in those cases. Here's a way (untested) to create a custom `wpse_link` filter for all the above cases of `get_permalink()`: foreach( [ 'post', 'page', 'attachment', 'post_type' ] as $type ) { add_filter( $type . '_link', function ( $url, $post_id, ? bool $sample = null ) use ( $type ) { return apply_filters( 'wpse_link', $url, $post_id, $sample, $type ); }, 9999, 3 ); } where we can now filter all cases with: add_filter( 'wpse_link', function( $url, $post_id, $sample, $type ) { return $url; }, 10, 4 );
stackexchange-wordpress
{ "answer_score": 11, "question_score": 6, "tags": "permalinks, filters" }
how to auto fille conatct form 7 when user is logined I want to auto fill some details in contact 7 form , when user is logined and how to pass php value to js. **in function.php** if ( is_user_logged_in() ) { echo 'Welcome, registered user!'; $current_user = wp_get_current_user(); $custemail = $current_user->user_email; function get_user_fild_details(){ ?> <script type="text/javascript"> function codeAddress() { var phoneMaddy = '<?php echo $custemail; ?>'; alert('ok'); document.getElementById('nameMaddyC').value=phoneMaddy; } window.onload = codeAddress; </script> <?php } add_action("wp_head", "get_user_fild_details"); }
you can do with jquery like: <?php global $current_user; get_currentuserinfo(); echo 'Username: ' . $current_user->user_login . "\n"; echo 'User email: ' . $current_user->user_email . "\n"; echo 'User level: ' . $current_user->user_level . "\n"; echo 'User first name: ' . $current_user->user_firstname . "\n"; echo 'User last name: ' . $current_user->user_lastname . "\n"; echo 'User display name: ' . $current_user->display_name . "\n"; echo 'User ID: ' . $current_user->ID . "\n"; ?> first get all login user data and then get contact form field id like #unsemae $("#unsemae").val("<?php echo $current_user->user_login ;?>"); Thnk you
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, javascript, plugin contact form 7, autocomplete" }
WP Rest API v2 filter and display latest post with specific tag I need to display the latest post with a specific tag. Example: User tags a post 'featured', but forgets to untag earlier posts. So I want to ensure that the latest post tagged 'featured' is what displays on other sites. <
You can actually find extensive documentation on wordpress.org. But let's have a look at this particular example: The `5` in there is the number of posts you want returned. The `3` is the id of the tag you want to limit the posts too. If you want to limit to a category use `categories` instead. But you'd have figured that out yourself after looking at the documentation, right? ;-)
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "posts, json, rest api, wp api" }
Return date in French $current_post['date'] = get_the_date( $smof_data['blog-date_format'] ); echo $current_post['date']; I would like to display the date in french. How can I do that using de code above?
Bonjour :) you can use the function `date_i18n`, e.g. like this $dateToDisplay = time(); echo date_i18n(get_option("date_format"), $dateToDisplay); look in the codex for more informations <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "date" }
Display posts using post ID's in an array I currently have an array of post ID's stored as **$recenty_viewed** that looks like this: Array ( [0] => 3164 [1] => 3165 [2] => 3168 [3] => 3176 ) I'd like to display each post thumbnail and title using the ID's above, but I can't seem to figure out how to get the data from each post. Any idea?
Get post thumbnail by id = get_the_post_thumbnail($id); Get the title by id = get_the_title($id);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, array" }
Including admin-options.php file in Child Themes My theme uses the following in functions.php > require_once get_template_directory() . '/includes/admin-options.php'; I want to override this with my own version of the admin-options.php file, which I have stored in my Child Theme directory. As per Codex instructions on Referencing / Including Files in Your Child Theme I've tried adding the following line in my Child Theme functions.php file > require_once( get_stylesheet_directory() . '/admin-options.php' ); both with and without commenting out the require_once line in the theme functions.php file. Neither way works - the site won't load at all. Echoing the line in my Child Theme functions.php gives the correct path for the admin-options.php file I want to include: > echo ( get_stylesheet_directory() . '/admin-options.php'); returns wp-content/themes/onetone-child/admin-options.php What am I missing?
I think that in wordpress you can't override a file of functions of a parent theme, the only thing that can do is to make an override of the functions of this file in your functions.php of your child theme. if ( ! function_exists ( 'my_function' ) ) { function my_function() { // Contents of your function here. } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, child theme, include" }
create a template page for a post i am new in wordpress and i am sorry for my english. May be my title is wrong. sorry for that. My question is like that. I have too many custom post types. I need some pages for a specific custom post type. For example: I have musics, books and movies. I want to create a template for them like that; < < How can I do that? Thank you for helping and sorry for my english.
You can add a rewrite tag and rules that capture anything after the post name: function wpd_add_rewrites(){ add_rewrite_tag( '%my_page%', '(.+)' ); $post_types = array( 'movie', 'book', 'album' ); foreach( $post_types as $post_type ){ add_rewrite_rule( '^' . $post_type . '/([^/]*)/([^/]*)/?', 'index.php?post_type=' . $post_type . '&name=$matches[1]&my_page=$matches[2]', 'top' ); } } add_action( 'init', 'wpd_add_rewrites' ); Don't forget, you must flush rewrite rules after adding / changing them. You can do this quickly by just visiting the Settings > Permalinks page. You can then check the value of `my_page` anywhere after the `wp` action: echo get_query_var( 'my_page' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, pages, page template" }
Wrong product thumbnail size I have set the Thumbanil size to 112px, but the page is rendering the original size instead ![1]( That is why the thumbanil is so pixelated The thumbnails show just fine in Firefox: !2 What could be wrong? maybe the Media Image settings are in conflict with the Product Image settings? ![3]( ![4](
Did you try to upload a new image and when uploading image checked what size it getting into image size in media? You can also try custom thumbnail size: add_image_size('products_image', 112, 112, true); and enque it into loop.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "woocommerce offtopic, thumbnails" }
How to create post in WP network using WP-CLI How create post using _WP-CLI_ at time of network site create. I am creating network sites using _WP-CLI_. I have tried: wp post create --post_type=page --post_title='ABC' --post_status=publish --network But it creates post on main site. But, I want to create that post on network site which was created that time. Thanks in advance. Any reference will be helpful.
You can try the `--url` argument to target a given **site** in your network: wp post create \ --post_type=page \ --post_title='ABC' \ --post_status=publish \ --url= where you can view available site urls with wp site list
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "posts, multisite, wp cli" }
How to include jQuery when no header and footer on the page I have a plugin page, which doesn't have `header.php` or `footer.php`. How can I include Wordpress jQuery on this page so I can use syntax like below ? jQuery(document).ready(function() { alert('hello'); }); At the moment it says: Uncaught ReferenceError: jQuery is not defined
Though uncommon, you can use `wp_print_scripts( ['jquery'] )` for explicit output. Note that you might hit issues with hooks firing in unexpected ways and such. _Generally_ all WP pages on front end should just implement header/footer properly.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "jquery" }
How to Pull ALL Posts, Categories, or Tags in WordPress REST API I have read other posts on this forum and none of which I read are solving my problem. Whenever I do: < Or even: < It still returns 10 posts. The same is happening when I try to get the Categories, or the Tags. I have a request to pull ALL categories, tags, and posts from the REST API as a single list.
According to the documentation, the correct argument is `per_page`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "rest api" }
Split reads to a different connection string Anyone know if there's a way to catch the database connection object, and change the connection string under it? Basically I want to redirect the commands that don't have the words INSERT, UPDATE, DELETE, EXECUTE or EXEC to another server name which would be a load balancer of sorts. I browsed the docs, but couldn't find anything that looked right. That said, I'm not a developer by trade.
You can use Wordpress HyperDB plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, database" }
add_filter : Passing an array instead of the callback function? I was just reading through BuddyPress code because I want to develop a custom plugin on top of it. I encountered something very peculiar that I haven't seen before and cannot seem to find any material on. The following code is from a protected function under a class named `BP_Legacy` // Filter BuddyPress template hierarchy and look for page templates. add_filter( 'bp_get_buddypress_template', array( $this, 'theme_compat_page_templates' ), 10, 1 ); As far as I know, the syntax for `add_filter` is something like add_filter ('hook_name', 'callback_function', $priority, $number_of_arguments) How is it that an array has been passed instead of the callback function? How exactly would this line of code run?
You can pass as the callback argument anything which is callable by PHP definition, something that might actually change between PHP versions. In this specific case the `array($o,$m)` type of notation indicates that the filter will call `$o->$m`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugin development, filters, buddypress" }
Restrict content piece by role - Protection message in content? I use below function (`Nothing here` is protection message): function show_user_content($atts,$content = null){ global $post; if (current_user_can('subscriber')){ return $content; } return "Nothing here"; } add_shortcode('RESTRICTROLE','show_user_content'); Then in post content: [RESTRICTROLE]some word for subscriber[/RESTRICTROLE] I need to be able to write the protection message in post content instead of in function. My goal is to use multiple protection message by using single function.
Shortcode API supports arbitrary attributes, so you could easily implement it with one like: [RESTRICTROLE message="Really nothing here"]some word for subscriber[/RESTRICTROLE]
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles, conditional content" }
Infinite scroll function for Twenty Seventeen It doesn't look like the Twenty Seventeen theme supports Infinite Scroll, and adding support doesn't work either if I add the following to `functions.php`: add_theme_support( 'infinite-scroll', array( 'container' => 'content', 'footer' => 'page', ) ); That just results in a "Load more" button but clicking it results in the button disappearing and no further posts being loaded. Is it possible to add support for this in the Twenty Seventeen theme?
Well, I really should've done this to begin with, but I took a look at my NGINX logs while the infinite scroll would hang, and it turns out the NAXSI web application firewall module I'm using in NGINX is blocking infinite scroll due to anti-XSS/ant-SQL injection policies. Specifically it's because of square brackets and usage of the word "update". Hopefully this will help anyone else out on Google with a similar issue, but here is what I added to the WordPress NAXSI whitelist to allow infinite scroll: BasicRule wl:1310,1311 "mz:$BODY_VAR:scripts[]|NAME"; BasicRule wl:1310,1311 "mz:$BODY_VAR:styles[]|NAME"; BasicRule wl:1310,1311 "mz:$BODY_VAR_X:^query_args\[.*\]|NAME"; BasicRule wl:1000 "mz:$BODY_VAR:query_args[update_post_term_cache]|NAME"; BasicRule wl:1000 "mz:$BODY_VAR:query_args[update_post_meta_cache]|NAME";
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin jetpack, infinite scroll, theme twenty seventeen" }
Problem with using custom shortcode with ACF WYSIWYG field I have created a custom shortcode `[colored-list]` to simply print an HTML code template. The reason to build this shortcode is because I am using PHP loop in it to print the list of text in different color sets based on the item count. So e.g. first text will be red, second blue, third yellow, fourth again red,...blue, yellow. So this is how I have built a color cycle for every text. I have created lot more shortcodes for different purposes but above one is just for example. Now what I am doing is, I have created a WYSIWYG editor using Advanced Custom Field plugin to add some more content. And I am using this shortcode in it. But every time I echo it on frontend, it prints with `P` tags added to so many places. I have tried so many fixes like removing wpautop filter, applying "the_content" filter etc. But none of them helped.
I got it fixed with below code :) $section_content = get_sub_field('section_content', false, false); $section_content = apply_filters('the_content', $section_content);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "shortcode, advanced custom fields, wysiwyg" }