qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
248,787 |
<p>I made a short code in my plugin that pulls out one of the custom post featured image from one taxonomy term each, the taxonomy term under which the post is in, and two term metas.</p>
<p>I want the term of that taxonomy to be limited to only a certain number of characters e.g. 12 but my code below does not truncate the long name of that term and add an ellipses as i am trying below.</p>
<pre><code>ob_start();
$post_type = 'esitykset';
$taxonomy = 'tapahtumat';
$post_ids = get_unique_term_recent_posts( $post_type, $taxonomy );
if ( $post_ids ) {
$args = [
'post__in' => $post_ids,
'post_type' => $post_type,
'posts_per_page' => 8
];
$q = new WP_Query( $args );
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
?>
<div class="home-poster-column">
<?php
$thumb = '';
$width = (int) apply_filters( 'et_pb_index_blog_image_width', 724 );
$height = (int) apply_filters( 'et_pb_index_blog_image_height', 1024 );
$classtext = 'et_pb_post_main_image';
$titletext = get_the_title();
$thumbnail = get_thumbnail( $width, $height, $classtext, $titletext, $titletext, false, 'Blogimage' );
$thumb = $thumbnail["thumb"];
?>
<?php
global $term_link;
if ( $terms = get_the_terms( $term_link->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
}
?>
<a href="<?php echo get_term_link( $term ); ?>">
<span class="esitys-poster">
<?php print_thumbnail( $thumb, $thumbnail["use_timthumb"], $titletext, $width, $height ); ?>
</span><br/>
<strong>
<?php
$event = the_terms( $post->ID, 'tapahtumat');
$len = 10; // <-- Adjust to your needs!
echo mb_strimwidth($event, 0, $len, 'UTF8' ) . '&hellip;';
?>
</strong> <br/>
<?php
/*
Get the date range meta of tapahtumat taxonomy
http://wordpress.stackexchange.com/questions/11820/echo-custom-taxonomy-field-values-outside-the-loop
*/
global $date_range;
if ( $terms = get_the_terms( $date_range->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
echo get_term_meta( $term->term_id, 'date-range', true ) . '<br/>';
}
/* Get the start price meta of tapahtumat taxonomy */
global $start_price;
if ( $terms = get_the_terms( $start_price->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
echo get_term_meta( $term->term_id, 'start-price', true );
}
?>
</a>
</div>
<?php
wp_reset_postdata(); } // endif have_posts()
} // endif $post_ids
$myvariable = ob_get_clean();
return $myvariable;
</code></pre>
<p>I know that the code above is a little twisted. Please feel free to suggest better ways if you feel is better approach.</p>
<p>Thanks</p>
|
[
{
"answer_id": 248791,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>This is not working because <code>the_terms()</code> is echo-ing the output.</p>\n\n<p>It would make more sense to trim down the lengthy term names, instead of doing it directly on the HTML output of <code>get_the_term_list()</code> that's used by <code>get_the_terms()</code>. That could give unvalid HTML, that could break the layout of your site.</p>\n\n<p>Here's an example for the corresponding theme file:</p>\n\n<pre><code>// Add a filter\nadd_filter( 'get_the_terms', 'wpse248787_get_the_terms' );\n\n// Display terms\nthe_terms( get_the_ID(), 'tapahtumat' );\n\n// Remove the filter again\nremove_filter( 'get_the_terms', 'wpse248787_get_the_terms' );\n</code></pre>\n\n<p>where you have defined:</p>\n\n<pre><code>function wpse248787_get_the_terms( $terms )\n{\n $len = 10; // <-- Adjust to your needs!\n\n // Limit term names if needed\n foreach( $terms as $term )\n {\n if( $len > 0 && $len < mb_strlen( $term->name ) )\n $term->name = mb_substr( $term->name, 0, $len - 1, 'UTF8' ) . '&hellip;';\n }\n\n return $terms;\n}\n</code></pre>\n\n<p>in the <code>functions.php</code> file in the current theme directory. You might also need to addjust the encoding argument or use e.g. <code>get_option( 'blog_charset' )</code>.</p>\n"
},
{
"answer_id": 248792,
"author": "Emil",
"author_id": 80532,
"author_profile": "https://wordpress.stackexchange.com/users/80532",
"pm_score": 1,
"selected": false,
"text": "<p><code>the_terms()</code> will <em>not</em> return anything – it will display the terms and return false or nothing.</p>\n\n<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_term_list\" rel=\"nofollow noreferrer\"><code>get_the_term_list()</code></a> to get the full HTML for the terms to be displayed. Use <code>get_the_terms()</code> to get an array of the terms.<br>\nIt's hard to understand what you mean by \"limit the characters to 12\" - do you want to limit <em>each</em> term to 12 characters, or the total string after the terms have been concatenated into a string?</p>\n\n<p>Also, <code>mb_strlen()</code> is not the function you're looking for, it only gives you the length of the provided string, you should be using <a href=\"http://php.net/manual/en/function.mb-strwidth.php\" rel=\"nofollow noreferrer\"><code>mb_strimwidth()</code></a>:</p>\n\n<pre><code>string mb_strimwidth ( string $str , int $start , int $width [, string $trimmarker = \"\" [, string $encoding = mb_internal_encoding() ]] )\n</code></pre>\n"
}
] |
2016/12/09
|
[
"https://wordpress.stackexchange.com/questions/248787",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77779/"
] |
I made a short code in my plugin that pulls out one of the custom post featured image from one taxonomy term each, the taxonomy term under which the post is in, and two term metas.
I want the term of that taxonomy to be limited to only a certain number of characters e.g. 12 but my code below does not truncate the long name of that term and add an ellipses as i am trying below.
```
ob_start();
$post_type = 'esitykset';
$taxonomy = 'tapahtumat';
$post_ids = get_unique_term_recent_posts( $post_type, $taxonomy );
if ( $post_ids ) {
$args = [
'post__in' => $post_ids,
'post_type' => $post_type,
'posts_per_page' => 8
];
$q = new WP_Query( $args );
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
?>
<div class="home-poster-column">
<?php
$thumb = '';
$width = (int) apply_filters( 'et_pb_index_blog_image_width', 724 );
$height = (int) apply_filters( 'et_pb_index_blog_image_height', 1024 );
$classtext = 'et_pb_post_main_image';
$titletext = get_the_title();
$thumbnail = get_thumbnail( $width, $height, $classtext, $titletext, $titletext, false, 'Blogimage' );
$thumb = $thumbnail["thumb"];
?>
<?php
global $term_link;
if ( $terms = get_the_terms( $term_link->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
}
?>
<a href="<?php echo get_term_link( $term ); ?>">
<span class="esitys-poster">
<?php print_thumbnail( $thumb, $thumbnail["use_timthumb"], $titletext, $width, $height ); ?>
</span><br/>
<strong>
<?php
$event = the_terms( $post->ID, 'tapahtumat');
$len = 10; // <-- Adjust to your needs!
echo mb_strimwidth($event, 0, $len, 'UTF8' ) . '…';
?>
</strong> <br/>
<?php
/*
Get the date range meta of tapahtumat taxonomy
http://wordpress.stackexchange.com/questions/11820/echo-custom-taxonomy-field-values-outside-the-loop
*/
global $date_range;
if ( $terms = get_the_terms( $date_range->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
echo get_term_meta( $term->term_id, 'date-range', true ) . '<br/>';
}
/* Get the start price meta of tapahtumat taxonomy */
global $start_price;
if ( $terms = get_the_terms( $start_price->ID, 'tapahtumat' ) ) {
// $term = $terms[0]; // WRONG! $terms is indexed by term ID!
$term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array
echo get_term_meta( $term->term_id, 'start-price', true );
}
?>
</a>
</div>
<?php
wp_reset_postdata(); } // endif have_posts()
} // endif $post_ids
$myvariable = ob_get_clean();
return $myvariable;
```
I know that the code above is a little twisted. Please feel free to suggest better ways if you feel is better approach.
Thanks
|
This is not working because `the_terms()` is echo-ing the output.
It would make more sense to trim down the lengthy term names, instead of doing it directly on the HTML output of `get_the_term_list()` that's used by `get_the_terms()`. That could give unvalid HTML, that could break the layout of your site.
Here's an example for the corresponding theme file:
```
// Add a filter
add_filter( 'get_the_terms', 'wpse248787_get_the_terms' );
// Display terms
the_terms( get_the_ID(), 'tapahtumat' );
// Remove the filter again
remove_filter( 'get_the_terms', 'wpse248787_get_the_terms' );
```
where you have defined:
```
function wpse248787_get_the_terms( $terms )
{
$len = 10; // <-- Adjust to your needs!
// Limit term names if needed
foreach( $terms as $term )
{
if( $len > 0 && $len < mb_strlen( $term->name ) )
$term->name = mb_substr( $term->name, 0, $len - 1, 'UTF8' ) . '…';
}
return $terms;
}
```
in the `functions.php` file in the current theme directory. You might also need to addjust the encoding argument or use e.g. `get_option( 'blog_charset' )`.
|
248,814 |
<p>I know it's easy to disable Wordpress from adding both <code>p</code> and <code>br</code> tags with:</p>
<pre><code>remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
</code></pre>
<p>but I want Wordpress to keep adding <code><br></code> where there is a line break.
I only use text editor, visual editor is disabled.
It was working fine until the recent update to Wordpress 4.7 - now it is adding some closing <code>p</code> tags, without opening them like <code></p></code> .</p>
<p>even tried <a href="https://wordpress.org/plugins/disable-automatic-p-tags/" rel="nofollow noreferrer">this</a> plugin but it disables br tags as well.</p>
<p>Any way of just disabling <code>p</code> tags not <code>br</code> tags in post content? I can't find anything on the internet that says something about a solution.</p>
|
[
{
"answer_id": 252582,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 0,
"selected": false,
"text": "<p>The \"the_content\" filter is used to filter the content of the post where filter function in <code>your_prefix_ptagfix</code> forces to find the <code><p></code> tags before and after the shortcodes opening tags. </p>\n\n<p>Add The following code to your functions file and let me know if that helps.</p>\n\n<pre><code>add_action( 'after_setup_theme', 'your_prefix_theme_setup' );\nfunction your_prefix_theme_setup(){\n add_filter( 'the_content', 'your_prefix_ptagfix' );\n\n}\n\nfunction your_prefix_ptagfix($content){ \n $array = array (\n '<p>[' => '[', \n ']</p>' => ']',\n );\n\n $content = strtr($content, $array);\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 252583,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 4,
"selected": true,
"text": "<p>You'd better never disable those actions (what you say). Instead, insert <code>add_filter('the_content', 'MyFilter', 88 );</code> and create such function:</p>\n\n<pre><code>function MyFilter($content){\n $tags = array( 'p', 'span');\n ///////////////////////////////////////////////////\n ///////// HERE INSERT ANY OF BELOW CODE //////////\n ///////////////////////////////////////////////////\n return $content;\n}\n</code></pre>\n\n<h1>======== METHOD 1 =========</h1>\n\n<pre><code>$content= preg_replace( '#<(' . implode( '|', $tags) . ')(.*|)?>#si', '', $content);\n$content= preg_replace( '#<\\/(' . implode( '|', $tags) . ')>#si', '', $content);\n</code></pre>\n\n<h1>======== METHOD 2 ======</h1>\n\n<pre><code>foreach ($tags as $tag) {\n $content= preg_replace('#<\\s*' . $tag . '[^>]*>.*?<\\s*/\\s*'. $tag . '>#msi', '', $content);\n}\n</code></pre>\n\n<h1>======== METHOD 3 =========</h1>\n\n<p><strong>DOM</strong> object (preferred): <a href=\"https://stackoverflow.com/a/31380542/2377343\">https://stackoverflow.com/a/31380542/2377343</a></p>\n"
}
] |
2016/12/09
|
[
"https://wordpress.stackexchange.com/questions/248814",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6927/"
] |
I know it's easy to disable Wordpress from adding both `p` and `br` tags with:
```
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
```
but I want Wordpress to keep adding `<br>` where there is a line break.
I only use text editor, visual editor is disabled.
It was working fine until the recent update to Wordpress 4.7 - now it is adding some closing `p` tags, without opening them like `</p>` .
even tried [this](https://wordpress.org/plugins/disable-automatic-p-tags/) plugin but it disables br tags as well.
Any way of just disabling `p` tags not `br` tags in post content? I can't find anything on the internet that says something about a solution.
|
You'd better never disable those actions (what you say). Instead, insert `add_filter('the_content', 'MyFilter', 88 );` and create such function:
```
function MyFilter($content){
$tags = array( 'p', 'span');
///////////////////////////////////////////////////
///////// HERE INSERT ANY OF BELOW CODE //////////
///////////////////////////////////////////////////
return $content;
}
```
======== METHOD 1 =========
===========================
```
$content= preg_replace( '#<(' . implode( '|', $tags) . ')(.*|)?>#si', '', $content);
$content= preg_replace( '#<\/(' . implode( '|', $tags) . ')>#si', '', $content);
```
======== METHOD 2 ======
========================
```
foreach ($tags as $tag) {
$content= preg_replace('#<\s*' . $tag . '[^>]*>.*?<\s*/\s*'. $tag . '>#msi', '', $content);
}
```
======== METHOD 3 =========
===========================
**DOM** object (preferred): <https://stackoverflow.com/a/31380542/2377343>
|
248,826 |
<p>How can I use <code>.htaccess</code> to rewrite a a page on a subdomain to a page on the parent? (E.g. people visiting mysite.com/landingpage will see the content from dev.mysite.com/landingpage)?</p>
<p>Ive been working to redesign a WordPress site, using a dev.mysite.com subdomain. The site isn't ready to replace the live WP site yet (mysite.com) but I need to map one of the pages to the old domain and make it public. Since all the work (template,database,etc) is on the subdomain, I can't just import the page to the old domain, so I seemingly need to use <code>mod_rewrite</code>, which is way beyond my skill level.
Also, since its two different WP Installations (not multisite), would I use the domain <code>.htaccess</code> file or the subdomain <code>.htaccess</code> file?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 252582,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 0,
"selected": false,
"text": "<p>The \"the_content\" filter is used to filter the content of the post where filter function in <code>your_prefix_ptagfix</code> forces to find the <code><p></code> tags before and after the shortcodes opening tags. </p>\n\n<p>Add The following code to your functions file and let me know if that helps.</p>\n\n<pre><code>add_action( 'after_setup_theme', 'your_prefix_theme_setup' );\nfunction your_prefix_theme_setup(){\n add_filter( 'the_content', 'your_prefix_ptagfix' );\n\n}\n\nfunction your_prefix_ptagfix($content){ \n $array = array (\n '<p>[' => '[', \n ']</p>' => ']',\n );\n\n $content = strtr($content, $array);\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 252583,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 4,
"selected": true,
"text": "<p>You'd better never disable those actions (what you say). Instead, insert <code>add_filter('the_content', 'MyFilter', 88 );</code> and create such function:</p>\n\n<pre><code>function MyFilter($content){\n $tags = array( 'p', 'span');\n ///////////////////////////////////////////////////\n ///////// HERE INSERT ANY OF BELOW CODE //////////\n ///////////////////////////////////////////////////\n return $content;\n}\n</code></pre>\n\n<h1>======== METHOD 1 =========</h1>\n\n<pre><code>$content= preg_replace( '#<(' . implode( '|', $tags) . ')(.*|)?>#si', '', $content);\n$content= preg_replace( '#<\\/(' . implode( '|', $tags) . ')>#si', '', $content);\n</code></pre>\n\n<h1>======== METHOD 2 ======</h1>\n\n<pre><code>foreach ($tags as $tag) {\n $content= preg_replace('#<\\s*' . $tag . '[^>]*>.*?<\\s*/\\s*'. $tag . '>#msi', '', $content);\n}\n</code></pre>\n\n<h1>======== METHOD 3 =========</h1>\n\n<p><strong>DOM</strong> object (preferred): <a href=\"https://stackoverflow.com/a/31380542/2377343\">https://stackoverflow.com/a/31380542/2377343</a></p>\n"
}
] |
2016/12/09
|
[
"https://wordpress.stackexchange.com/questions/248826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68512/"
] |
How can I use `.htaccess` to rewrite a a page on a subdomain to a page on the parent? (E.g. people visiting mysite.com/landingpage will see the content from dev.mysite.com/landingpage)?
Ive been working to redesign a WordPress site, using a dev.mysite.com subdomain. The site isn't ready to replace the live WP site yet (mysite.com) but I need to map one of the pages to the old domain and make it public. Since all the work (template,database,etc) is on the subdomain, I can't just import the page to the old domain, so I seemingly need to use `mod_rewrite`, which is way beyond my skill level.
Also, since its two different WP Installations (not multisite), would I use the domain `.htaccess` file or the subdomain `.htaccess` file?
Thanks!
|
You'd better never disable those actions (what you say). Instead, insert `add_filter('the_content', 'MyFilter', 88 );` and create such function:
```
function MyFilter($content){
$tags = array( 'p', 'span');
///////////////////////////////////////////////////
///////// HERE INSERT ANY OF BELOW CODE //////////
///////////////////////////////////////////////////
return $content;
}
```
======== METHOD 1 =========
===========================
```
$content= preg_replace( '#<(' . implode( '|', $tags) . ')(.*|)?>#si', '', $content);
$content= preg_replace( '#<\/(' . implode( '|', $tags) . ')>#si', '', $content);
```
======== METHOD 2 ======
========================
```
foreach ($tags as $tag) {
$content= preg_replace('#<\s*' . $tag . '[^>]*>.*?<\s*/\s*'. $tag . '>#msi', '', $content);
}
```
======== METHOD 3 =========
===========================
**DOM** object (preferred): <https://stackoverflow.com/a/31380542/2377343>
|
248,840 |
<p>I tried to update Wordpress to version 4.7 and received a fatal error. I'm using windows and XAMPP for localhost development.</p>
<pre><code>Update WordPress
Downloading update from
https://downloads.wordpress.org/release/wordpress-4.7-new-bundled.zip…
Unpacking the update…
Fatal error: Maximum execution time of 30 seconds exceeded in
<path to project>\wp-admin\includes\class-wp-filesystem-direct.php on line 81
</code></pre>
<p>Inside class-wp-file-system-direct.php (line 81 is if-statement):</p>
<pre><code>public function put_contents( $file, $contents, $mode = false ) {
$fp = @fopen( $file, 'wb' );
if ( ! $fp )
return false;
mbstring_binary_safe_encoding();
$data_length = strlen( $contents );
$bytes_written = fwrite( $fp, $contents );
reset_mbstring_encoding();
fclose( $fp );
if ( $data_length !== $bytes_written ) // LINE 81
return false;
$this->chmod( $file, $mode );
return true;
}
</code></pre>
<p>I removed read-only permissions from the includes folder and the file itself and explicitly allowed write permission on the file. I ran the auto update for Wordpress again, and now I'm getting.</p>
<pre><code>Update WordPress
Another update is currently in progress.
</code></pre>
<p>Not sure what to try next.</p>
<p><strong>Solved</strong></p>
<p>Manually updating Wordpress solved the problem.</p>
|
[
{
"answer_id": 248872,
"author": "nu everest",
"author_id": 106850,
"author_profile": "https://wordpress.stackexchange.com/users/106850",
"pm_score": 2,
"selected": true,
"text": "<p><strong>Manually updating Wordpress fixes this issue.</strong> </p>\n\n<p><strong><em>Upgrading WordPress Core Manually (How To)</em></strong> <a href=\"https://www.wordfence.com/learn/how-to-manually-upgrade-wordpress-themes-and-plugins/\" rel=\"nofollow noreferrer\">WordFence Reference</a></p>\n\n<ul>\n<li>First create a full backup of your website. This is very important in\ncase you make a mistake.</li>\n<li>Download the newest WordPress ZIP file from wordpress.org. Unzip the\nfile into a directory on your local machine or in a separate\ndirectory on your website.</li>\n<li>Deactivate all of the plugins on your WordPress site.</li>\n<li>Go to your website root directory and delete your ‘wp-includes’ and\n‘wp-admin’ directories. You can do this via sFTP or via SSH.</li>\n<li>Upload (or copy over) the new wp-includes and wp-admin directories\nfrom the new version of WordPress you unzipped to your website root\ndirectory to replace the directories you just deleted.</li>\n<li>Don’t delete your wp-content directory or any of the files in that\ndirectory. Copy over the files from the wp-content directory in the\nnew version of WordPress to your existing wp-content directory. You\nwill overwrite any existing files with the same name. All of your\nother files in wp-content will remain in place.</li>\n<li>Copy all files from the root (‘/’) directory of the new version of\nWordPress that you unzipped into your website root directory (or the\nroot directory of your WordPress installation). You will overwrite\nany existing files and new files will also be copied across. Your\nwp-config.php file will not be affected because WordPress is never\ndistributed with a wp-config.php file.</li>\n<li>Examine the wp-config-sample.php which is distributed with WordPress\nto see if any new settings have been added that you may want to use\nor modify.</li>\n<li>If you are upgrading manually after a failed auto-update, remove the\n.maintenance file from your WordPress root directory. This will\nremove the ‘failed update’ message from your site.</li>\n<li>Visit your main WordPress admin page at /wp-admin/ where you may be\nasked to sign-in again. You may also have to upgrade your database\nand will be prompted if this is needed. If you can’t sign-in, try\nclearing your cookies. Re-enable your plugins which you disabled\nearlier.</li>\n<li>Clear your browser cache to ensure you can see all changes. If you\nare using a front-end cache like ‘varnish’ you should also clear that\nto ensure that your customers can see the newest changes on your\nsite.</li>\n<li>Your upgrade is now complete and you should be running the newest\nversion of WordPress.</li>\n</ul>\n"
},
{
"answer_id": 262071,
"author": "Din Mohammed pabel",
"author_id": 116372,
"author_profile": "https://wordpress.stackexchange.com/users/116372",
"pm_score": 1,
"selected": false,
"text": "<p>Please</p>\n\n<p>locate the file [XAMPP Installation Directory]\\php\\php.ini (e.g. C:\\xampp\\php\\php.ini)</p>\n\n<ol>\n<li><p>open php.ini in Notepad or any Text editor</p></li>\n<li><p>locate the line containing max_execution_time and</p></li>\n<li><p>increase the value from 30 to some larger number (e.g. set: max_execution_time = 90)</p></li>\n<li><p>then restart Apache web server from the XAMPP control panel</p></li>\n</ol>\n\n<p>If there will still be the same error after that, try to increase the value for the max_execution_time further more.</p>\n"
},
{
"answer_id": 275759,
"author": "jreis",
"author_id": 124042,
"author_profile": "https://wordpress.stackexchange.com/users/124042",
"pm_score": 0,
"selected": false,
"text": "<p>You can see <a href=\"https://wordpress.stackexchange.com/questions/275749/getting-a-fatal-error-while-updating/275750\">here</a> the proper way to handle with the max execution time issues.</p>\n"
}
] |
2016/12/09
|
[
"https://wordpress.stackexchange.com/questions/248840",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106850/"
] |
I tried to update Wordpress to version 4.7 and received a fatal error. I'm using windows and XAMPP for localhost development.
```
Update WordPress
Downloading update from
https://downloads.wordpress.org/release/wordpress-4.7-new-bundled.zip…
Unpacking the update…
Fatal error: Maximum execution time of 30 seconds exceeded in
<path to project>\wp-admin\includes\class-wp-filesystem-direct.php on line 81
```
Inside class-wp-file-system-direct.php (line 81 is if-statement):
```
public function put_contents( $file, $contents, $mode = false ) {
$fp = @fopen( $file, 'wb' );
if ( ! $fp )
return false;
mbstring_binary_safe_encoding();
$data_length = strlen( $contents );
$bytes_written = fwrite( $fp, $contents );
reset_mbstring_encoding();
fclose( $fp );
if ( $data_length !== $bytes_written ) // LINE 81
return false;
$this->chmod( $file, $mode );
return true;
}
```
I removed read-only permissions from the includes folder and the file itself and explicitly allowed write permission on the file. I ran the auto update for Wordpress again, and now I'm getting.
```
Update WordPress
Another update is currently in progress.
```
Not sure what to try next.
**Solved**
Manually updating Wordpress solved the problem.
|
**Manually updating Wordpress fixes this issue.**
***Upgrading WordPress Core Manually (How To)*** [WordFence Reference](https://www.wordfence.com/learn/how-to-manually-upgrade-wordpress-themes-and-plugins/)
* First create a full backup of your website. This is very important in
case you make a mistake.
* Download the newest WordPress ZIP file from wordpress.org. Unzip the
file into a directory on your local machine or in a separate
directory on your website.
* Deactivate all of the plugins on your WordPress site.
* Go to your website root directory and delete your ‘wp-includes’ and
‘wp-admin’ directories. You can do this via sFTP or via SSH.
* Upload (or copy over) the new wp-includes and wp-admin directories
from the new version of WordPress you unzipped to your website root
directory to replace the directories you just deleted.
* Don’t delete your wp-content directory or any of the files in that
directory. Copy over the files from the wp-content directory in the
new version of WordPress to your existing wp-content directory. You
will overwrite any existing files with the same name. All of your
other files in wp-content will remain in place.
* Copy all files from the root (‘/’) directory of the new version of
WordPress that you unzipped into your website root directory (or the
root directory of your WordPress installation). You will overwrite
any existing files and new files will also be copied across. Your
wp-config.php file will not be affected because WordPress is never
distributed with a wp-config.php file.
* Examine the wp-config-sample.php which is distributed with WordPress
to see if any new settings have been added that you may want to use
or modify.
* If you are upgrading manually after a failed auto-update, remove the
.maintenance file from your WordPress root directory. This will
remove the ‘failed update’ message from your site.
* Visit your main WordPress admin page at /wp-admin/ where you may be
asked to sign-in again. You may also have to upgrade your database
and will be prompted if this is needed. If you can’t sign-in, try
clearing your cookies. Re-enable your plugins which you disabled
earlier.
* Clear your browser cache to ensure you can see all changes. If you
are using a front-end cache like ‘varnish’ you should also clear that
to ensure that your customers can see the newest changes on your
site.
* Your upgrade is now complete and you should be running the newest
version of WordPress.
|
248,851 |
<p>I have allow readers to select the posts order with different parameters. For a example users can order posts by "vote". (Vote is a custom post type.) </p>
<p>Then URL will be <code>http://example.com/?sort_by_type=vote</code></p>
<p>I have used <code>pre_get_posts</code> action to do orderthe posts. It works fine. The problem is pagination .</p>
<p>Pagination look like this in my theme.</p>
<pre><code>http://example.com/?sort_by_type=vote/page/2/
</code></pre>
<p>But it should be <code>http://example.com/page/2/?sort_by_type=vote</code> to work correctly. </p>
<p>So how I correct pagination?</p>
<hr>
<p>Edit After comment of @govind : The theme which I used is a not a theme developed by me. What I did i, if URL contain <code>?sort_by_type=vote</code> request I changed the post order using <code>pre_get_posts</code> filter.</p>
<p>When I cheeking theme I found following code. </p>
<pre><code><?php if ( is_home() || is_archive() || is_search() ) : // If viewing the blog, an archive, or search results. ?>
<?php loop_pagination(
array(
'prev_text' => _x( '&larr; Previous', 'posts navigation', 'daily' ),
'next_text' => _x( 'Next &rarr;', 'posts navigation', 'daily' )
)
); ?>
<?php endif; ?>
</code></pre>
|
[
{
"answer_id": 248852,
"author": "Mostafa Soufi",
"author_id": 106877,
"author_profile": "https://wordpress.stackexchange.com/users/106877",
"pm_score": 0,
"selected": false,
"text": "<p>You should define a new pagination function for do it.</p>\n\n<pre><code><?php\nfunction custom_pagination() {\n\n if( is_singular() )\n return;\n\n global $wp_query;\n\n /** Stop execution if there's only 1 page */\n if( $wp_query->max_num_pages <= 1 )\n return;\n\n $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;\n $max = intval( $wp_query->max_num_pages );\n\n /** Add current page to the array */\n if ( $paged >= 1 )\n $links[] = $paged;\n\n /** Add the pages around the current page to the array */\n if ( $paged >= 3 ) {\n $links[] = $paged - 1;\n $links[] = $paged - 2;\n }\n\n if ( ( $paged + 2 ) <= $max ) {\n $links[] = $paged + 2;\n $links[] = $paged + 1;\n }\n\n echo '<div class=\"navigation\"><ul>' . \"\\n\";\n\n /** Previous Post Link */\n if ( get_previous_posts_link() )\n printf( '<li>%s</li>' . \"\\n\", get_previous_posts_link() );\n\n /** Link to first page, plus ellipses if necessary */\n if ( ! in_array( 1, $links ) ) {\n $class = 1 == $paged ? ' class=\"active\"' : '';\n\n printf( '<li%s><a href=\"%s\">%s?sort_by_type=vote</a></li>' . \"\\n\", $class, esc_url( get_pagenum_link( 1 ) ), '1' );\n\n if ( ! in_array( 2, $links ) )\n echo '<li>…</li>';\n }\n\n /** Link to current page, plus 2 pages in either direction if necessary */\n sort( $links );\n foreach ( (array) $links as $link ) {\n $class = $paged == $link ? ' class=\"active\"' : '';\n printf( '<li%s><a href=\"%s\">%s?sort_by_type=vote</a></li>' . \"\\n\", $class, esc_url( get_pagenum_link( $link ) ), $link );\n }\n\n /** Link to last page, plus ellipses if necessary */\n if ( ! in_array( $max, $links ) ) {\n if ( ! in_array( $max - 1, $links ) )\n echo '<li>…</li>' . \"\\n\";\n\n $class = $paged == $max ? ' class=\"active\"' : '';\n printf( '<li%s><a href=\"%s\">%s?sort_by_type=vote</a></li>' . \"\\n\", $class, esc_url( get_pagenum_link( $max ) ), $max );\n }\n\n /** Next Post Link */\n if ( get_next_posts_link() )\n printf( '<li>%s</li>' . \"\\n\", get_next_posts_link() );\n\n echo '</ul></div>' . \"\\n\";\n\n}\n</code></pre>\n"
},
{
"answer_id": 248854,
"author": "GKS",
"author_id": 90674,
"author_profile": "https://wordpress.stackexchange.com/users/90674",
"pm_score": 3,
"selected": true,
"text": "<p>You can create your custom pagination using <code>paginate_link()</code> function and add custom query string after current url.</p>\n\n<p>To add argument to the links of paginations you can pass them as array argument inside the 'add_args' </p>\n\n<pre><code>if ( is_home() || is_archive() || is_search() ) : \n\n echo paginate_links(array(\n 'base' => preg_replace('/\\?.*/', '/', get_pagenum_link(1)) . '%_%',\n 'current' => max(1, get_query_var('paged')),\n 'format' => 'page/%#%',\n 'total' => $wp_query->max_num_pages,\n // here you can pass custom query string to the pagination url\n 'add_args' => array(\n 'sort_by_type' => ( !empty($_GET['sort_by_type']) ) ? $_GET['sort_by_type'] : 'vote'\n )\n )); \n\nendif; \n</code></pre>\n\n<p>Replace your pagination code with this above code.</p>\n\n<p>It will print all string with custom query string.\n<code>http://example.com/page/2/?sort_by_type=vote</code></p>\n\n<p>Hope this help! </p>\n"
}
] |
2016/12/10
|
[
"https://wordpress.stackexchange.com/questions/248851",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106350/"
] |
I have allow readers to select the posts order with different parameters. For a example users can order posts by "vote". (Vote is a custom post type.)
Then URL will be `http://example.com/?sort_by_type=vote`
I have used `pre_get_posts` action to do orderthe posts. It works fine. The problem is pagination .
Pagination look like this in my theme.
```
http://example.com/?sort_by_type=vote/page/2/
```
But it should be `http://example.com/page/2/?sort_by_type=vote` to work correctly.
So how I correct pagination?
---
Edit After comment of @govind : The theme which I used is a not a theme developed by me. What I did i, if URL contain `?sort_by_type=vote` request I changed the post order using `pre_get_posts` filter.
When I cheeking theme I found following code.
```
<?php if ( is_home() || is_archive() || is_search() ) : // If viewing the blog, an archive, or search results. ?>
<?php loop_pagination(
array(
'prev_text' => _x( '← Previous', 'posts navigation', 'daily' ),
'next_text' => _x( 'Next →', 'posts navigation', 'daily' )
)
); ?>
<?php endif; ?>
```
|
You can create your custom pagination using `paginate_link()` function and add custom query string after current url.
To add argument to the links of paginations you can pass them as array argument inside the 'add\_args'
```
if ( is_home() || is_archive() || is_search() ) :
echo paginate_links(array(
'base' => preg_replace('/\?.*/', '/', get_pagenum_link(1)) . '%_%',
'current' => max(1, get_query_var('paged')),
'format' => 'page/%#%',
'total' => $wp_query->max_num_pages,
// here you can pass custom query string to the pagination url
'add_args' => array(
'sort_by_type' => ( !empty($_GET['sort_by_type']) ) ? $_GET['sort_by_type'] : 'vote'
)
));
endif;
```
Replace your pagination code with this above code.
It will print all string with custom query string.
`http://example.com/page/2/?sort_by_type=vote`
Hope this help!
|
248,877 |
<p>How do I add the date before the entry title in Twenty Twelve with just functions.php?</p>
<p>Right now I have to add and modify many files in the child theme such as content.php, content-aside.php, content-image.php, content-link.php, content-quote.php, content-status.php. </p>
<p>Is there a way to do it with filters? I tried to put it in the_content but the date displays below the title. </p>
|
[
{
"answer_id": 248878,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>the_title</code> filter. Example below.</p>\n\n<pre><code>function display_extra_title( $title, $id = null ) {\n\n $date = the_date();\n\n return $date . $title;\n}\nadd_filter( 'the_title', 'display_extra_title', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 248921,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>Base on @Tunji answer.\nYou can add some conditions to the function to detect home-page, feeds...</p>\n\n<pre><code>function display_extra_title( $title, $id = null ) {\n\n $date = the_date('', '', '', false);\n\n if(is_home()){\n $title = get_bloginfo( 'name' );\n return $date . $title;\n }\n else{\n return $date . $title;\n }\n\n}\nadd_filter( 'the_title', 'display_extra_title', 10, 2 );\n</code></pre>\n\n<p>In order to properly return <code>the_date</code> and not echoing it, you must set the last parameter to false. See more details <a href=\"https://codex.wordpress.org/Function_Reference/the_date\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>If you don't want to display the date in the menu widget... You can surround <code>$date</code> in a span and add css to not display it when it's the menu, sidebar...</p>\n\n<pre><code>$title = '<span class=\"title_date\">'.$date.'</span> '.$title;\n</code></pre>\n\n<p>In the css (adjust and add all what you need:</p>\n\n<pre><code>.sidebar .title_date{ display:none;}\n</code></pre>\n"
}
] |
2016/12/10
|
[
"https://wordpress.stackexchange.com/questions/248877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87509/"
] |
How do I add the date before the entry title in Twenty Twelve with just functions.php?
Right now I have to add and modify many files in the child theme such as content.php, content-aside.php, content-image.php, content-link.php, content-quote.php, content-status.php.
Is there a way to do it with filters? I tried to put it in the\_content but the date displays below the title.
|
Base on @Tunji answer.
You can add some conditions to the function to detect home-page, feeds...
```
function display_extra_title( $title, $id = null ) {
$date = the_date('', '', '', false);
if(is_home()){
$title = get_bloginfo( 'name' );
return $date . $title;
}
else{
return $date . $title;
}
}
add_filter( 'the_title', 'display_extra_title', 10, 2 );
```
In order to properly return `the_date` and not echoing it, you must set the last parameter to false. See more details [here](https://codex.wordpress.org/Function_Reference/the_date)
If you don't want to display the date in the menu widget... You can surround `$date` in a span and add css to not display it when it's the menu, sidebar...
```
$title = '<span class="title_date">'.$date.'</span> '.$title;
```
In the css (adjust and add all what you need:
```
.sidebar .title_date{ display:none;}
```
|
248,900 |
<p>I have successfully translated a child theme, but not the same result in mu-plugins folder.</p>
<p>The name of the plugin is "mu-functions.php".
In this file I have added the "Text Domain: mu-functions" in the header and then I have loaded the textdomain:</p>
<pre><code>add_action( 'plugins_loaded', 'myplugin_muload_textdomain' );
function myplugin_muload_textdomain() {
load_muplugin_textdomain( 'mu-functions', basename( dirname(__FILE__) ) . '/inc/languages' );
}
</code></pre>
<p>The structure of the plugin that I have created in the mu-plugins directory is the following:</p>
<p>In the same directory I have a "inc"(include) folder where I put all the other files that are being called through the "include_once()" function in "mu-function.php" file.
Along with this files, in the same "inc" folder directory, I have the "languages" folder where I have created the "mu-functions.pot" file that has been translated to Portuguese and then generated to both ".mo" and ".po" files.</p>
<p>In my child theme I had an issue with these ".mo" and ".po" files. I have found in another forum that I had to name them only by the locale (so in this case "pt_PT") and not "Text-Domain-pt_PT". This issue has been successfully solved.
Being so, for testing purposes I have generated 2 more other ".mo" and ".po" files.
These are the files that are in my languages folder:</p>
<ul>
<li>mu-functions-pt_PT.mo</li>
<li>mu-functions-pt_PT.po</li>
<li>mu-functions.pot</li>
<li>pt_PT.mo</li>
<li>pt_PT.po</li>
</ul>
<p>Can anybody, please, help me? What am I missing?</p>
|
[
{
"answer_id": 248887,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 6,
"selected": true,
"text": "<p>4.7 has it enabled by default. The easy way to check if it is working is just to visit the example.com/wp-json url, and you should get a list of registered end points there</p>\n<p>There is no official option to disable it as (at least there was a talk about it not sure if it got in the release), some core functionality depends on it.</p>\n<p>The most obvious things to check for if it is not working is your htaccess rules, and do you have a wp-json directory</p>\n<p>Also, if <code>/wp-json/wp/v2/posts</code> type URLs don't work for you, but <code>/?rest_route=/wp-json/wp/v2/posts</code> does, it means you need to enable pretty permalinks in the settings (suggested by Giles Butler in comments below).</p>\n"
},
{
"answer_id": 249535,
"author": "friendlyfire",
"author_id": 86684,
"author_profile": "https://wordpress.stackexchange.com/users/86684",
"pm_score": 1,
"selected": false,
"text": "<p>I see you have fixed the issue but leaving my solution here as it worked for me too. I had this same issue when updating from beta15 to the core api in wp 4.7 Turns out the issue was that I had some plugins that were using a deprecated function register_api_field which I changed to register_rest_field according to this note in the changelog:</p>\n\n<blockquote>\n <p>BREAKING CHANGE: Rename register_api_field() to register_rest_field().</p>\n \n <p>Introduces a register_api_field() function for backwards compat, which\n calls _doing_it_wrong(). However, register_api_field() won't ever be\n committed to WordPress core, so you should update your function calls.</p>\n</blockquote>\n"
},
{
"answer_id": 271438,
"author": "Edward",
"author_id": 122654,
"author_profile": "https://wordpress.stackexchange.com/users/122654",
"pm_score": 4,
"selected": false,
"text": "<p>I had 4.7 also thought that REST API was disabled, but I was tricked by the URL. To see the correct URL seek a line looking something like that:</p>\n\n<p>link rel='<code>https://api.w.org/</code>' href='<code>http://mysite?rest_route=/</code>' />. \nSo, using <a href=\"http://mysite?rest_route=/\" rel=\"noreferrer\">http://mysite?rest_route=/</a> as the prefix solved my problem. For instance to recover the posts is enought to type: <a href=\"http://mysite?rest_route=/wp/json\" rel=\"noreferrer\">http://mysite?rest_route=/wp/json</a></p>\n\n<p>I couldn't find on documentation that the query param was needed. Was I the only one?</p>\n"
},
{
"answer_id": 339101,
"author": "samjco",
"author_id": 29133,
"author_profile": "https://wordpress.stackexchange.com/users/29133",
"pm_score": 3,
"selected": false,
"text": "<p>If REST API isn't working out-of-box or after a fresh install and after typing in </p>\n\n<pre><code>mydomain/wp-json/wp/v2/posts \n</code></pre>\n\n<p>then you would need to simply activate your \"permalinks\" as post_name located: </p>\n\n<p>WP Dashboard->Settings->Permalinks</p>\n\n<p>Or if you do not wish to activate permalinks, you can simply type:</p>\n\n<pre><code>mydomain?rest_route=/wp/v2/posts\n</code></pre>\n\n<p>Man, I wish WordPress would update their Rest handbook to be more user-friendly. I like the old version of docs :)</p>\n"
}
] |
2016/12/10
|
[
"https://wordpress.stackexchange.com/questions/248900",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108695/"
] |
I have successfully translated a child theme, but not the same result in mu-plugins folder.
The name of the plugin is "mu-functions.php".
In this file I have added the "Text Domain: mu-functions" in the header and then I have loaded the textdomain:
```
add_action( 'plugins_loaded', 'myplugin_muload_textdomain' );
function myplugin_muload_textdomain() {
load_muplugin_textdomain( 'mu-functions', basename( dirname(__FILE__) ) . '/inc/languages' );
}
```
The structure of the plugin that I have created in the mu-plugins directory is the following:
In the same directory I have a "inc"(include) folder where I put all the other files that are being called through the "include\_once()" function in "mu-function.php" file.
Along with this files, in the same "inc" folder directory, I have the "languages" folder where I have created the "mu-functions.pot" file that has been translated to Portuguese and then generated to both ".mo" and ".po" files.
In my child theme I had an issue with these ".mo" and ".po" files. I have found in another forum that I had to name them only by the locale (so in this case "pt\_PT") and not "Text-Domain-pt\_PT". This issue has been successfully solved.
Being so, for testing purposes I have generated 2 more other ".mo" and ".po" files.
These are the files that are in my languages folder:
* mu-functions-pt\_PT.mo
* mu-functions-pt\_PT.po
* mu-functions.pot
* pt\_PT.mo
* pt\_PT.po
Can anybody, please, help me? What am I missing?
|
4.7 has it enabled by default. The easy way to check if it is working is just to visit the example.com/wp-json url, and you should get a list of registered end points there
There is no official option to disable it as (at least there was a talk about it not sure if it got in the release), some core functionality depends on it.
The most obvious things to check for if it is not working is your htaccess rules, and do you have a wp-json directory
Also, if `/wp-json/wp/v2/posts` type URLs don't work for you, but `/?rest_route=/wp-json/wp/v2/posts` does, it means you need to enable pretty permalinks in the settings (suggested by Giles Butler in comments below).
|
248,904 |
<p>I'm new at this.</p>
<p>I need a shortcode that returns the post id of the post in which the shortcode is inserted.</p>
<p>If someone could provide that it would open the doors of understanding for me :)</p>
<p>Much appreciated!</p>
|
[
{
"answer_id": 248907,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 4,
"selected": true,
"text": "<p>Place the below code to your themes <code>functions.php</code> or inside your plugin and the <code>[return_post_id]</code> shortcode will print the post ID.</p>\n\n<pre><code>add_shortcode( 'return_post_id', 'the_dramatist_return_post_id' );\n\nfunction the_dramatist_return_post_id() {\n return get_the_ID();\n}\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 273428,
"author": "Antonio Marcos",
"author_id": 123894,
"author_profile": "https://wordpress.stackexchange.com/users/123894",
"pm_score": 0,
"selected": false,
"text": "<p>Shortcode: Embeddable Post Excerpts</p>\n\n<p>After installing the shortcode (follow steps 1 + 2 below) you can execute it anywhere WordPress accepts shortcodes. To connect to a post, you simply need to enter the post ID you wish to display:</p>\n\n<p><a href=\"https://marketersdelight.net/snippets/embeddable-excerpts/\" rel=\"nofollow noreferrer\">https://marketersdelight.net/snippets/embeddable-excerpts/</a></p>\n"
}
] |
2016/12/11
|
[
"https://wordpress.stackexchange.com/questions/248904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108215/"
] |
I'm new at this.
I need a shortcode that returns the post id of the post in which the shortcode is inserted.
If someone could provide that it would open the doors of understanding for me :)
Much appreciated!
|
Place the below code to your themes `functions.php` or inside your plugin and the `[return_post_id]` shortcode will print the post ID.
```
add_shortcode( 'return_post_id', 'the_dramatist_return_post_id' );
function the_dramatist_return_post_id() {
return get_the_ID();
}
```
Hope that helps.
|
248,957 |
<p>This is my code in functions.php for adding the custom field in comment form</p>
<pre><code>add_filter( 'comment_form_default_fields', 'add_phonenumber_field' );
function add_phonenumber_field($fields) {
$fields['phonenumber'] = '<p class="comment-form-phonenumber"><label for="phonenumber">Phone Number <span class="required">*</span></label>' .
'<input id="phone-number" name="phone-number" type="tel" pattern="[\+]\d{2}[\(]\d{3}[\)]\d{3}[\-]\d{4}" title="Phone Number (Format: +63(123)456-7980)" aria-required="true" required="required"/></p>';
return $fields;
}
</code></pre>
<p>This is how comment form looks like now
<a href="https://i.stack.imgur.com/h6uOO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h6uOO.png" alt="enter image description here"></a></p>
<p>But when I send the comment and click edit in the Dashboard under Comments tab, no phone number field is there.
<a href="https://i.stack.imgur.com/7UTKg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7UTKg.png" alt="enter image description here"></a></p>
<p>How can I make it appear in when I edit the comment and display it in the approved comments on the front-end?
Thanks for help!</p>
|
[
{
"answer_id": 248907,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 4,
"selected": true,
"text": "<p>Place the below code to your themes <code>functions.php</code> or inside your plugin and the <code>[return_post_id]</code> shortcode will print the post ID.</p>\n\n<pre><code>add_shortcode( 'return_post_id', 'the_dramatist_return_post_id' );\n\nfunction the_dramatist_return_post_id() {\n return get_the_ID();\n}\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 273428,
"author": "Antonio Marcos",
"author_id": 123894,
"author_profile": "https://wordpress.stackexchange.com/users/123894",
"pm_score": 0,
"selected": false,
"text": "<p>Shortcode: Embeddable Post Excerpts</p>\n\n<p>After installing the shortcode (follow steps 1 + 2 below) you can execute it anywhere WordPress accepts shortcodes. To connect to a post, you simply need to enter the post ID you wish to display:</p>\n\n<p><a href=\"https://marketersdelight.net/snippets/embeddable-excerpts/\" rel=\"nofollow noreferrer\">https://marketersdelight.net/snippets/embeddable-excerpts/</a></p>\n"
}
] |
2016/12/12
|
[
"https://wordpress.stackexchange.com/questions/248957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90228/"
] |
This is my code in functions.php for adding the custom field in comment form
```
add_filter( 'comment_form_default_fields', 'add_phonenumber_field' );
function add_phonenumber_field($fields) {
$fields['phonenumber'] = '<p class="comment-form-phonenumber"><label for="phonenumber">Phone Number <span class="required">*</span></label>' .
'<input id="phone-number" name="phone-number" type="tel" pattern="[\+]\d{2}[\(]\d{3}[\)]\d{3}[\-]\d{4}" title="Phone Number (Format: +63(123)456-7980)" aria-required="true" required="required"/></p>';
return $fields;
}
```
This is how comment form looks like now
[](https://i.stack.imgur.com/h6uOO.png)
But when I send the comment and click edit in the Dashboard under Comments tab, no phone number field is there.
[](https://i.stack.imgur.com/7UTKg.png)
How can I make it appear in when I edit the comment and display it in the approved comments on the front-end?
Thanks for help!
|
Place the below code to your themes `functions.php` or inside your plugin and the `[return_post_id]` shortcode will print the post ID.
```
add_shortcode( 'return_post_id', 'the_dramatist_return_post_id' );
function the_dramatist_return_post_id() {
return get_the_ID();
}
```
Hope that helps.
|
248,967 |
<p>We can get posts from a category using below request</p>
<pre><code> `/wp/v2/posts?categories=1&search=somequery`
</code></pre>
<p>It only gives results from category(1) only. How can we get results from category(1) and from all subcategories of category(1) also? Than You.</p>
|
[
{
"answer_id": 248972,
"author": "Emil",
"author_id": 80532,
"author_profile": "https://wordpress.stackexchange.com/users/80532",
"pm_score": 0,
"selected": false,
"text": "<p>You'll need to do an additional call to find the IDs of the subcategories – there is no way to get posts from subcategories by only including the parent category in the search.</p>\n\n<pre><code>/wp/v2/categories?parent=ID&per_page=0&\n</code></pre>\n\n<p>This call will return an array of category objects, grab the IDs of those objects and pass them to your request for posts:</p>\n\n<pre><code>/wp/v2/posts?categories=1,A,B,C,D&search=somequery\n</code></pre>\n"
},
{
"answer_id": 381962,
"author": "Myo Win",
"author_id": 49962,
"author_profile": "https://wordpress.stackexchange.com/users/49962",
"pm_score": 1,
"selected": false,
"text": "<p>This answer has what you want <a href=\"https://wordpress.stackexchange.com/a/314152/49962\">https://wordpress.stackexchange.com/a/314152/49962</a></p>\n<p>WP already does this out of the box thanks to the include_children parameter of tax_query which is true by default.</p>\n<p>So you do not need to tell it the sub-terms, just do something like this:</p>\n<pre><code>/wp/v2/posts?categories=1\n</code></pre>\n<p>Where <code>categories=1</code> is the parent category ID</p>\n"
}
] |
2016/12/12
|
[
"https://wordpress.stackexchange.com/questions/248967",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107444/"
] |
We can get posts from a category using below request
```
`/wp/v2/posts?categories=1&search=somequery`
```
It only gives results from category(1) only. How can we get results from category(1) and from all subcategories of category(1) also? Than You.
|
This answer has what you want <https://wordpress.stackexchange.com/a/314152/49962>
WP already does this out of the box thanks to the include\_children parameter of tax\_query which is true by default.
So you do not need to tell it the sub-terms, just do something like this:
```
/wp/v2/posts?categories=1
```
Where `categories=1` is the parent category ID
|
248,983 |
<p>I'm using the following form html to generate a search function on a wordpress site:</p>
<pre><code><form method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="search&hellip;" maxlength="50" required="required" />
<button type="submit">Search</button>
</fieldset>
</form>
</code></pre>
<p>It works ok, but I wish to only return results for a specific custom post type. I'm using the search.php template from twentysixteen theme which contains this:</p>
<pre><code><?php global $wp_query; ?>
<h1 class="search-title"><?php echo $wp_query->found_posts; ?> Results found for: <span><?php the_search_query(); ?></span></h1>
<?php if ( have_posts() ) { ?>
<ul class="results">
<?php while ( have_posts() ) { the_post(); ?>
<li>
<?php if ( has_post_thumbnail() ) { ?><div class="post-image"><a href="<?php echo get_permalink(); ?>"><?php the_post_thumbnail('thumbnail');?></a></div><?php }?>
<div class="post-content">
<h3><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h3>
<p><?php echo substr(get_the_excerpt(), 0,140); ?>... <a href="<?php the_permalink(); ?>">Read More</a></p>
</div>
</li>
<?php } ?>
</ul>
<?php } ?>
</code></pre>
<p>Is there a variable that I can add somewhere to only return results for a specific post type? Thanks</p>
|
[
{
"answer_id": 248984,
"author": "The Sumo",
"author_id": 76021,
"author_profile": "https://wordpress.stackexchange.com/users/76021",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, so I did a little more digging around and it turns out to be pretty easy. I just needed to add a hidden input into the search form. Posting this here for anyone else looking for the answer:</p>\n\n<pre><code><form class=\"search\" action=\"<?php echo home_url( '/' ); ?>\">\n <input type=\"search\" name=\"s\" placeholder=\"Search&hellip;\">\n <input type=\"submit\" value=\"Search\">\n <input type=\"hidden\" name=\"post_type\" value=\"custom-post-type\">\n</form>\n</code></pre>\n\n<p>Obviously you will need to replace the value \"custom-post-type\" with your own custom post type.</p>\n"
},
{
"answer_id": 249004,
"author": "tormorten",
"author_id": 49832,
"author_profile": "https://wordpress.stackexchange.com/users/49832",
"pm_score": 3,
"selected": false,
"text": "<p>A more elegant solution would be to modify the main query itself by using the <code>pre_get_posts</code> action.</p>\n\n<pre><code><?php \n\nfunction my_pre_get_posts($query) {\n\n if( is_admin() ) \n return;\n\n if( is_search() && $query->is_main_query() ) {\n $query->set('post_type', 'custom-post-type-name');\n } \n\n}\n\nadd_action( 'pre_get_posts', 'my_pre_get_posts' );\n</code></pre>\n\n<p>This would require no change in the template.</p>\n"
}
] |
2016/12/12
|
[
"https://wordpress.stackexchange.com/questions/248983",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76021/"
] |
I'm using the following form html to generate a search function on a wordpress site:
```
<form method="get" action="<?php bloginfo('url'); ?>">
<fieldset>
<input type="text" name="s" value="" placeholder="search…" maxlength="50" required="required" />
<button type="submit">Search</button>
</fieldset>
</form>
```
It works ok, but I wish to only return results for a specific custom post type. I'm using the search.php template from twentysixteen theme which contains this:
```
<?php global $wp_query; ?>
<h1 class="search-title"><?php echo $wp_query->found_posts; ?> Results found for: <span><?php the_search_query(); ?></span></h1>
<?php if ( have_posts() ) { ?>
<ul class="results">
<?php while ( have_posts() ) { the_post(); ?>
<li>
<?php if ( has_post_thumbnail() ) { ?><div class="post-image"><a href="<?php echo get_permalink(); ?>"><?php the_post_thumbnail('thumbnail');?></a></div><?php }?>
<div class="post-content">
<h3><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h3>
<p><?php echo substr(get_the_excerpt(), 0,140); ?>... <a href="<?php the_permalink(); ?>">Read More</a></p>
</div>
</li>
<?php } ?>
</ul>
<?php } ?>
```
Is there a variable that I can add somewhere to only return results for a specific post type? Thanks
|
Ok, so I did a little more digging around and it turns out to be pretty easy. I just needed to add a hidden input into the search form. Posting this here for anyone else looking for the answer:
```
<form class="search" action="<?php echo home_url( '/' ); ?>">
<input type="search" name="s" placeholder="Search…">
<input type="submit" value="Search">
<input type="hidden" name="post_type" value="custom-post-type">
</form>
```
Obviously you will need to replace the value "custom-post-type" with your own custom post type.
|
248,991 |
<p>I'm making a plugin where the user can order something. But before he has to confirm his email, so I'm sending out that mail with the confirmation link, something like that: <code>mydomain.com/myconfirmation?token=MYTOKEN</code></p>
<p>How do I fetch this confirmation url <code>myconfirmation</code> in WordPress without the website owner having to create an extra page for this?</p>
|
[
{
"answer_id": 248984,
"author": "The Sumo",
"author_id": 76021,
"author_profile": "https://wordpress.stackexchange.com/users/76021",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, so I did a little more digging around and it turns out to be pretty easy. I just needed to add a hidden input into the search form. Posting this here for anyone else looking for the answer:</p>\n\n<pre><code><form class=\"search\" action=\"<?php echo home_url( '/' ); ?>\">\n <input type=\"search\" name=\"s\" placeholder=\"Search&hellip;\">\n <input type=\"submit\" value=\"Search\">\n <input type=\"hidden\" name=\"post_type\" value=\"custom-post-type\">\n</form>\n</code></pre>\n\n<p>Obviously you will need to replace the value \"custom-post-type\" with your own custom post type.</p>\n"
},
{
"answer_id": 249004,
"author": "tormorten",
"author_id": 49832,
"author_profile": "https://wordpress.stackexchange.com/users/49832",
"pm_score": 3,
"selected": false,
"text": "<p>A more elegant solution would be to modify the main query itself by using the <code>pre_get_posts</code> action.</p>\n\n<pre><code><?php \n\nfunction my_pre_get_posts($query) {\n\n if( is_admin() ) \n return;\n\n if( is_search() && $query->is_main_query() ) {\n $query->set('post_type', 'custom-post-type-name');\n } \n\n}\n\nadd_action( 'pre_get_posts', 'my_pre_get_posts' );\n</code></pre>\n\n<p>This would require no change in the template.</p>\n"
}
] |
2016/12/12
|
[
"https://wordpress.stackexchange.com/questions/248991",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92649/"
] |
I'm making a plugin where the user can order something. But before he has to confirm his email, so I'm sending out that mail with the confirmation link, something like that: `mydomain.com/myconfirmation?token=MYTOKEN`
How do I fetch this confirmation url `myconfirmation` in WordPress without the website owner having to create an extra page for this?
|
Ok, so I did a little more digging around and it turns out to be pretty easy. I just needed to add a hidden input into the search form. Posting this here for anyone else looking for the answer:
```
<form class="search" action="<?php echo home_url( '/' ); ?>">
<input type="search" name="s" placeholder="Search…">
<input type="submit" value="Search">
<input type="hidden" name="post_type" value="custom-post-type">
</form>
```
Obviously you will need to replace the value "custom-post-type" with your own custom post type.
|
248,993 |
<p>I would like to order a list of post title alphabetically.
I am using this specific query </p>
<pre><code>// WP_Query arguments
$args = array(
'category_name' => 'reportage',
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query($args);
// The Loop
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo '<ul><li style="float:left; width:100%;"><a href="'.get_the_permalink().'" style="color:#D34D3D">'.get_the_title().'</a></li></ul>';
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
</code></pre>
<p>The query worked perfect until a certain point of the list where the order seems to be messed up. </p>
<p>Why the order doesn't work correctly for all the post title? </p>
|
[
{
"answer_id": 249002,
"author": "tormorten",
"author_id": 49832,
"author_profile": "https://wordpress.stackexchange.com/users/49832",
"pm_score": 2,
"selected": false,
"text": "<p>Try adding <code>'suppress_filters' => true</code> to your query args. Maybe you have a plugin that modifies the queries.</p>\n\n<p>You could also check if the posts out of order (the first one) is a sticky post. Sticky posts by default skip the order queue.</p>\n\n<p>You can disable this by adding <code>'ignore_sticky_posts' => true</code> to your query args.</p>\n"
},
{
"answer_id": 366397,
"author": "zod",
"author_id": 143945,
"author_profile": "https://wordpress.stackexchange.com/users/143945",
"pm_score": 1,
"selected": false,
"text": "<p>Problem is $args, do this:</p>\n\n<pre><code>$args = array(\n 'category_name' => 'reportage',\n 'orderby' => array( 'title' => 'ASC' )\n);\n</code></pre>\n\n<p>You can also order by multiple parameters, like:</p>\n\n<pre><code>$args = array(\n 'category_name' => 'reportage',\n 'orderby' => array( 'menu_order' => 'ASC', 'title' => 'ASC', 'post_date' => 'DESC' ),\n);\n</code></pre>\n"
},
{
"answer_id": 382329,
"author": "philip",
"author_id": 196257,
"author_profile": "https://wordpress.stackexchange.com/users/196257",
"pm_score": 2,
"selected": false,
"text": "<p>I came across the same problem and could not figure it out. Eventually found the problem when I took a look at the custom post type entries in the database and noticed that the results that were out of order had values set in the menu_order column. After a bit of digging I realised that it was the Post Types Order plugin that was set to auto and 'injecting' an additional parameter to the orderby parameter. I understand you can turn off the auto function in the plugin settings but I opted to do it via the query parameters:</p>\n<pre><code>$loop = new WP_Query(\n array(\n 'post_type' => 'my-custom-post-type', \n 'order' => 'ASC', \n 'orderby' => 'title',\n 'ignore_custom_sort' => true\n ) \n); \n</code></pre>\n<p>And BINGO! the results came back in the correct order. Hope this helps someone.</p>\n"
}
] |
2016/12/12
|
[
"https://wordpress.stackexchange.com/questions/248993",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103072/"
] |
I would like to order a list of post title alphabetically.
I am using this specific query
```
// WP_Query arguments
$args = array(
'category_name' => 'reportage',
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query($args);
// The Loop
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo '<ul><li style="float:left; width:100%;"><a href="'.get_the_permalink().'" style="color:#D34D3D">'.get_the_title().'</a></li></ul>';
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
```
The query worked perfect until a certain point of the list where the order seems to be messed up.
Why the order doesn't work correctly for all the post title?
|
Try adding `'suppress_filters' => true` to your query args. Maybe you have a plugin that modifies the queries.
You could also check if the posts out of order (the first one) is a sticky post. Sticky posts by default skip the order queue.
You can disable this by adding `'ignore_sticky_posts' => true` to your query args.
|
248,998 |
<p>This is the code below I am using to create a table when installing plugin. But, I tried many ways and for some reason it is not working. Is there any other efficient way of doing this? Please Help, thanks in Advanced</p>
<pre><code>global $wpdb;
function creating_order_tables() {
global $wpdb;
$ptbd_table_name = $wpdb->prefix . 'printtextbd_order';
if ($wpdb->get_var("SHOW TABLES LIKE '". $ptbd_table_name ."'" ) != $ptbd_table_name ) {
$sql = 'CREATE TABLE exone(
customer_id INT(20) AUTO_INCREMENT,
customer_name VARCHAR(255),
order_type VARCHAR(255),
choosen_template VARCHAR(255),
order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(customer_id))';
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
echo "hello";
}
}
register_activation_hook(__FILE__, 'creating_order_tables');
</code></pre>
|
[
{
"answer_id": 248999,
"author": "Kamaro",
"author_id": 108796,
"author_profile": "https://wordpress.stackexchange.com/users/108796",
"pm_score": 2,
"selected": false,
"text": "<p>Try this one, Also remember int can have maximum of int(11)</p>\n\n<pre><code><?php\nglobal $wpdb;\n\n// Set table name\n$table = $wpdb->prefix . 'exone';\n\n$charset_collate = $wpdb->get_charset_collate();\n\n// Write creating query\n$query = \"CREATE TABLE IF NOT EXISTS \".$table.\" (\n customer_id INT(11) AUTO_INCREMENT,\n customer_name VARCHAR(255),\n order_type VARCHAR(255),\n choosen_template VARCHAR(255),\n order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n PRIMARY KEY(customer_id)\n )$charset_collate;\";\n\n// Execute the query\n$wpdb->query( $query );\n</code></pre>\n"
},
{
"answer_id": 249001,
"author": "tormorten",
"author_id": 49832,
"author_profile": "https://wordpress.stackexchange.com/users/49832",
"pm_score": 2,
"selected": true,
"text": "<p>Try using a different method. WordPress fires a hook during plugin activation <code>activate_yourplugin/filename.php</code>. You can use this to create tables.</p>\n\n<pre><code>function creating_order_tables() {\n\n if(!get_option('tables_created', false)) {\n\n global $wpdb;\n\n $ptbd_table_name = $wpdb->prefix . 'printtextbd_order';\n\n if ($wpdb->get_var(\"SHOW TABLES LIKE '\". $ptbd_table_name .\"'\" ) != $ptbd_table_name ) {\n\n $sql = 'CREATE TABLE exone(\n customer_id INT(20) AUTO_INCREMENT,\n customer_name VARCHAR(255),\n order_type VARCHAR(255),\n choosen_template VARCHAR(255),\n order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n PRIMARY KEY(customer_id))';\n\n if(!function_exists('dbDelta')) {\n require_once(ABSPATH . 'wp-admin/includes/upgrade.php');\n }\n\n dbDelta($sql);\n echo \"Tables created...\";\n update_option('tables_created', true);\n }\n }\n}\nadd_action('activate_yourplugin/yourplugin.php', 'creating_order_tables');\n</code></pre>\n"
}
] |
2016/12/12
|
[
"https://wordpress.stackexchange.com/questions/248998",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89234/"
] |
This is the code below I am using to create a table when installing plugin. But, I tried many ways and for some reason it is not working. Is there any other efficient way of doing this? Please Help, thanks in Advanced
```
global $wpdb;
function creating_order_tables() {
global $wpdb;
$ptbd_table_name = $wpdb->prefix . 'printtextbd_order';
if ($wpdb->get_var("SHOW TABLES LIKE '". $ptbd_table_name ."'" ) != $ptbd_table_name ) {
$sql = 'CREATE TABLE exone(
customer_id INT(20) AUTO_INCREMENT,
customer_name VARCHAR(255),
order_type VARCHAR(255),
choosen_template VARCHAR(255),
order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(customer_id))';
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
echo "hello";
}
}
register_activation_hook(__FILE__, 'creating_order_tables');
```
|
Try using a different method. WordPress fires a hook during plugin activation `activate_yourplugin/filename.php`. You can use this to create tables.
```
function creating_order_tables() {
if(!get_option('tables_created', false)) {
global $wpdb;
$ptbd_table_name = $wpdb->prefix . 'printtextbd_order';
if ($wpdb->get_var("SHOW TABLES LIKE '". $ptbd_table_name ."'" ) != $ptbd_table_name ) {
$sql = 'CREATE TABLE exone(
customer_id INT(20) AUTO_INCREMENT,
customer_name VARCHAR(255),
order_type VARCHAR(255),
choosen_template VARCHAR(255),
order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY(customer_id))';
if(!function_exists('dbDelta')) {
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
}
dbDelta($sql);
echo "Tables created...";
update_option('tables_created', true);
}
}
}
add_action('activate_yourplugin/yourplugin.php', 'creating_order_tables');
```
|
249,003 |
<p>I'm using the <code>WP_Customize_Cropped_Image_Control</code> for the user to upload and crop an image in the Customizer. However, the get theme mod function doesn't seem to be working for outputting it as I usually do.</p>
<p>This is what I have in my customizer.php file:</p>
<pre><code>$wp_customize->add_setting( 'bio_image', array(
'default' => get_template_directory_uri() . '/images/default.jpg',
'transport' => 'postMessage'
) );
$wp_customize->add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, 'bio_image', array(
'label' => __( 'bio_image', 'myTheme' ),
'flex_width' => false,
'flex_height' => false,
'width' => 200,
'height' => 200,
'settings' => 'bio_image',
) ) );
</code></pre>
<p>This is what I have in my template file:</p>
<pre><code><img src="<?php echo get_theme_mod( 'bio_image' , get_template_directory_uri().'/images/default.jpg' ); ?>">
</code></pre>
<p>This only displays the <code>default.jpg</code> image, and at the wrong dimensions.</p>
<p>Is there another way of outputting the cropped image?</p>
|
[
{
"answer_id": 249006,
"author": "Troy Templeman",
"author_id": 40536,
"author_profile": "https://wordpress.stackexchange.com/users/40536",
"pm_score": 0,
"selected": false,
"text": "<p>This did it for me, simplifying <a href=\"https://wordpress.stackexchange.com/users/8521/weston-ruter\">Weston's</a> answer above.</p>\n\n<pre><code><img id=\"bio-image\" src=\"<?php \n if ( get_theme_mod( 'bio_image' ) > 0 ) { \n echo wp_get_attachment_url( get_theme_mod( 'bio_image' ) ); \n } else { \n echo esc_url(get_template_directory_uri() . '/images/default.jpg'); \n } \n?>\">\n</code></pre>\n\n<p>However, the problem now is in the Customizer. The default image that I have set in <code>WP_Customize_Cropped_Image_Control</code> doesn't show up, nor does newly uploaded images because it outputs the image ID instead of the URL. The code I have below in my customizer.js is looking for the URL:</p>\n\n<pre><code>wp.customize( 'bio_image', function( value ) {\n value.bind( function( newval ) {\n $('#bio-image').attr( 'src', newval );\n } );\n} );\n</code></pre>\n\n<p>Does anyone know how to get the URL form the ID in jquery?</p>\n"
},
{
"answer_id": 249072,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 2,
"selected": false,
"text": "<p>The theme mod here is storing the attachment post ID whereas your default value is a URL. So what you'd need to do is something like:</p>\n\n<pre><code><?php\nfunction get_bio_image_url() {\n if ( get_theme_mod( 'bio_image' ) > 0 ) {\n return wp_get_attachment_url( get_theme_mod( 'bio_image' ) );\n } else {\n return get_template_directory_uri() . '/images/default.jpg';\n }\n}\n?>\n<img src=\"<?php echo esc_url( get_bio_image_url() ); ?>\">\n</code></pre>\n"
}
] |
2016/12/12
|
[
"https://wordpress.stackexchange.com/questions/249003",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40536/"
] |
I'm using the `WP_Customize_Cropped_Image_Control` for the user to upload and crop an image in the Customizer. However, the get theme mod function doesn't seem to be working for outputting it as I usually do.
This is what I have in my customizer.php file:
```
$wp_customize->add_setting( 'bio_image', array(
'default' => get_template_directory_uri() . '/images/default.jpg',
'transport' => 'postMessage'
) );
$wp_customize->add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, 'bio_image', array(
'label' => __( 'bio_image', 'myTheme' ),
'flex_width' => false,
'flex_height' => false,
'width' => 200,
'height' => 200,
'settings' => 'bio_image',
) ) );
```
This is what I have in my template file:
```
<img src="<?php echo get_theme_mod( 'bio_image' , get_template_directory_uri().'/images/default.jpg' ); ?>">
```
This only displays the `default.jpg` image, and at the wrong dimensions.
Is there another way of outputting the cropped image?
|
The theme mod here is storing the attachment post ID whereas your default value is a URL. So what you'd need to do is something like:
```
<?php
function get_bio_image_url() {
if ( get_theme_mod( 'bio_image' ) > 0 ) {
return wp_get_attachment_url( get_theme_mod( 'bio_image' ) );
} else {
return get_template_directory_uri() . '/images/default.jpg';
}
}
?>
<img src="<?php echo esc_url( get_bio_image_url() ); ?>">
```
|
249,015 |
<p>I have an issue with custom widgets and WordPress Coding Standards. When you create a custom widget, your class should have a "widget" method that will display the widget. Something like:</p>
<pre><code><?php
public function widget( $args, $instance ) {
echo $args['before_widget'];
?> <span><?php echo esc_html( 'Great widget', 'text-domain' ); ?></span> <?php
echo $args['after_widget'];
}
?>
</code></pre>
<p>While this is perfectly functional, this will not pass PHP code sniffer tests with WordPress coding standards because <code>$args['after_widget'];</code> and <code>$args['before_widget'];</code> are not escaped...</p>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 249020,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 4,
"selected": true,
"text": "<p>These arguments contain arbitrary HTML and cannot be properly escaped. This is essentially a limitation on how Widgets code was designed and you can see in core Widget classes that no escaping is done on these.</p>\n\n<p>Lessons to learn:</p>\n\n<ul>\n<li>WP core doesn't consistently adhere to its own coding standards (and getting there isn't considered worth targeted effort);</li>\n<li>passing around chunks of HTML is bad idea, in your own code pass <em>data</em> and render appropriately with proper escaping.</li>\n</ul>\n"
},
{
"answer_id": 249021,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": false,
"text": "<p>This is a problem with overly strict coding standards, not with how you should write wordpress code. In this context both parameters are assumed to be valid HTML (they are defined in sidebar registration time).</p>\n\n<p>Anyway in most tools like that there is a way to instruct the linter/sniffer to ignore that line or function. </p>\n\n<p>BTW the standards you are talking about are probably the wordpress.com VIP standards, not the wordpress one - <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/\" rel=\"noreferrer\">https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/</a></p>\n"
}
] |
2016/12/12
|
[
"https://wordpress.stackexchange.com/questions/249015",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76144/"
] |
I have an issue with custom widgets and WordPress Coding Standards. When you create a custom widget, your class should have a "widget" method that will display the widget. Something like:
```
<?php
public function widget( $args, $instance ) {
echo $args['before_widget'];
?> <span><?php echo esc_html( 'Great widget', 'text-domain' ); ?></span> <?php
echo $args['after_widget'];
}
?>
```
While this is perfectly functional, this will not pass PHP code sniffer tests with WordPress coding standards because `$args['after_widget'];` and `$args['before_widget'];` are not escaped...
What am I doing wrong?
|
These arguments contain arbitrary HTML and cannot be properly escaped. This is essentially a limitation on how Widgets code was designed and you can see in core Widget classes that no escaping is done on these.
Lessons to learn:
* WP core doesn't consistently adhere to its own coding standards (and getting there isn't considered worth targeted effort);
* passing around chunks of HTML is bad idea, in your own code pass *data* and render appropriately with proper escaping.
|
249,017 |
<p>I am trying to develop a method in my admin panel that will allow for the creation of a CSV file within the plugin directory
Here is my code: where $amount is the next increment of filename calculated beforehand (if 1.csv and 2.csv exist, then create 3.csv) this calculation works fine as I have tried echoing the filepath</p>
<pre><code> function createNewGallery($amount)
{
$files = $amount;
echo "CREATE NEW GALLERY";
$databaseURL = plugins_url( '/', __FILE__ );
$databaseURL .= $files + 1 . '.csv';
echo $databaseURL;
$headers = array('imageid', 'imgurl', 'IMGTEXT');
echo " $headers ";
$fp = fopen($databaseURL, 'w');
fwrite($fp, $headers);
fclose($fp);
}
</code></pre>
<p>The code above seems to execute but doesn't actually do anything. I want it to create the next iteration of the CSV in the directory specified and then push the headers to it, but looking at the live FTP nothing is happening </p>
|
[
{
"answer_id": 249019,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>Writing to a plugin directory is not considered a proper practice:</p>\n\n<ol>\n<li>Plugin directories are overwritten on plugin updates.</li>\n<li>They are also typically made read-only for web server in more security–conscious setups.</li>\n</ol>\n\n<p>The most easy location for write operations (as likely to be allowed as possible) in WP structure is uploads folder (<code>wp-content/uploads</code> by default, but should really be detected for current configuration).</p>\n\n<p>Also if the data is in least bit sensitive you should consider never leaving it in web accessible folder (which is all of WP structure is by design). You could generate in different location on server and serve from there or possibly just create and send to browser on the fly, without creating intermediary file.</p>\n"
},
{
"answer_id": 250273,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": true,
"text": "<p>If you plan to write to a pugin folder since you used <code>fopen</code>, <code>fwite</code>, <code>flose</code> you are using the wrong function:</p>\n\n<pre><code>File: wp-includes/link-template.php\n3189: /**\n3190: * Retrieves a URL within the plugins or mu-plugins directory.\n3191: *\n3192: * Defaults to the plugins directory URL if no arguments are supplied.\n3193: *\n3194: * @since 2.6.0\n3195: *\n3196: * @param string $path Optional. Extra path appended to the end of the URL, including\n3197: * the relative directory if $plugin is supplied. Default empty.\n3198: * @param string $plugin Optional. A full path to a file inside a plugin or mu-plugin.\n3199: * The URL will be relative to its directory. Default empty.\n3200: * Typically this is done by passing `__FILE__` as the argument.\n3201: * @return string Plugins URL link with optional paths appended.\n3202: */\n3203: function plugins_url( $path = '', $plugin = '' ) {\n3204: \n</code></pre>\n\n<p>You should probable use this function:</p>\n\n<pre><code>File: wp-includes/plugin.php\n703: /**\n704: * Get the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in.\n705: *\n706: * @since 2.8.0\n707: *\n708: * @param string $file The filename of the plugin (__FILE__).\n709: * @return string the filesystem path of the directory that contains the plugin.\n710: */\n711: function plugin_dir_path( $file ) {\n712: return trailingslashit( dirname( $file ) );\n713: }\n</code></pre>\n\n<p>Then you are on your own:</p>\n\n<pre><code>$plugin_dir = plugin_dir_path( __FILE__ );\n$logfile = $plugin_dir . 'log.csv';\n\n$fp = fopen($logfile, 'w');\nfwrite($fp, $data);\nfclose($fp);\n</code></pre>\n\n<blockquote>\n <p>At the moment plugins in WordPress have all the rights WordPress have when writing to a file system, and these are the rights given from the web server process.</p>\n</blockquote>\n\n<hr>\n\n<p>Your naming convention is not perfect: <code>$databaseURL</code> is probably bad chosen. This is not a URL.</p>\n"
}
] |
2016/12/12
|
[
"https://wordpress.stackexchange.com/questions/249017",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107110/"
] |
I am trying to develop a method in my admin panel that will allow for the creation of a CSV file within the plugin directory
Here is my code: where $amount is the next increment of filename calculated beforehand (if 1.csv and 2.csv exist, then create 3.csv) this calculation works fine as I have tried echoing the filepath
```
function createNewGallery($amount)
{
$files = $amount;
echo "CREATE NEW GALLERY";
$databaseURL = plugins_url( '/', __FILE__ );
$databaseURL .= $files + 1 . '.csv';
echo $databaseURL;
$headers = array('imageid', 'imgurl', 'IMGTEXT');
echo " $headers ";
$fp = fopen($databaseURL, 'w');
fwrite($fp, $headers);
fclose($fp);
}
```
The code above seems to execute but doesn't actually do anything. I want it to create the next iteration of the CSV in the directory specified and then push the headers to it, but looking at the live FTP nothing is happening
|
If you plan to write to a pugin folder since you used `fopen`, `fwite`, `flose` you are using the wrong function:
```
File: wp-includes/link-template.php
3189: /**
3190: * Retrieves a URL within the plugins or mu-plugins directory.
3191: *
3192: * Defaults to the plugins directory URL if no arguments are supplied.
3193: *
3194: * @since 2.6.0
3195: *
3196: * @param string $path Optional. Extra path appended to the end of the URL, including
3197: * the relative directory if $plugin is supplied. Default empty.
3198: * @param string $plugin Optional. A full path to a file inside a plugin or mu-plugin.
3199: * The URL will be relative to its directory. Default empty.
3200: * Typically this is done by passing `__FILE__` as the argument.
3201: * @return string Plugins URL link with optional paths appended.
3202: */
3203: function plugins_url( $path = '', $plugin = '' ) {
3204:
```
You should probable use this function:
```
File: wp-includes/plugin.php
703: /**
704: * Get the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in.
705: *
706: * @since 2.8.0
707: *
708: * @param string $file The filename of the plugin (__FILE__).
709: * @return string the filesystem path of the directory that contains the plugin.
710: */
711: function plugin_dir_path( $file ) {
712: return trailingslashit( dirname( $file ) );
713: }
```
Then you are on your own:
```
$plugin_dir = plugin_dir_path( __FILE__ );
$logfile = $plugin_dir . 'log.csv';
$fp = fopen($logfile, 'w');
fwrite($fp, $data);
fclose($fp);
```
>
> At the moment plugins in WordPress have all the rights WordPress have when writing to a file system, and these are the rights given from the web server process.
>
>
>
---
Your naming convention is not perfect: `$databaseURL` is probably bad chosen. This is not a URL.
|
249,034 |
<p>I'm using a theme that I've pulled from WordPress' repo (example: <a href="https://wordpress.org/themes/twentysixteen/" rel="nofollow noreferrer">Twenty Sixteen</a>), the default URL structure looks like so:</p>
<pre><code>http://example.com/wp-content/themes/twentysixteen/...
</code></pre>
<p>I want to hide any reference that this WordPress theme is coming from Twenty Sixteen and customize the directory to something else:</p>
<pre><code>http://example.com/wp-content/themes/my-site/...
</code></pre>
<p>While I can FTP to my website and rename the folder manually, I noticed that the theme does not receive any updates that are made on WordPress' repo.</p>
<p>I'd assume I would create a <a href="https://codex.wordpress.org/Child_Themes" rel="nofollow noreferrer">child theme</a> referring to Twenty Sixteen in order to still receive the latest updates for the theme and still have a custom directory name. Is that the best route?</p>
|
[
{
"answer_id": 249036,
"author": "Carl Willis",
"author_id": 69413,
"author_profile": "https://wordpress.stackexchange.com/users/69413",
"pm_score": 2,
"selected": true,
"text": "<p>changing the theme folder I guess it won't affect on updates but changing it's name do.</p>\n\n<p>So like you said the best way that every professional company advice is to create a child-theme and modify everything you want on it.</p>\n"
},
{
"answer_id": 249041,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>WordPress does submit directory names (child and parent) with update check data.</p>\n\n<p>Since updater is black box and its logic is refused to be disclosed, it's impossible to be certain if changing folder name <em>will</em> affect updates, but it certainly <em>can</em>.</p>\n\n<p>Basically if you modify theme then it's your problem to maintain it.</p>\n\n<p>You could try to mask paths with rewrite on web server level or maintain updates with non–WP tool, such as Composer.</p>\n\n<p>Overall I would question utility of obscuring the source here. If someone <em>wants</em> to figure out original publicly available theme you used — they <em>will</em>.</p>\n"
},
{
"answer_id": 250242,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>I checked in practice.\nI cloned a theme folder so I have now:</p>\n<pre><code>twentyseventeen\ntwentyseventeen (copy)\n</code></pre>\n<p>I opened the page <code>/wp-admin/themes.php</code>\nBoth the themes are up to date.</p>\n<p>I set the version from style.css file low to 0.1 for both.\nI refreshed the page <code>/wp-admin/themes.php</code></p>\n<p>I have the feedback now only a single theme have the update.</p>\n<h3><code>New version available. Update now</code></h3>\n<p>Only the theme stored in a folder <code>twentyseventeen</code> had the update.</p>\n<blockquote>\n<p>I didn't have to call <code>wp_update_themes();</code> since it worked instantly.</p>\n</blockquote>\n"
}
] |
2016/12/12
|
[
"https://wordpress.stackexchange.com/questions/249034",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] |
I'm using a theme that I've pulled from WordPress' repo (example: [Twenty Sixteen](https://wordpress.org/themes/twentysixteen/)), the default URL structure looks like so:
```
http://example.com/wp-content/themes/twentysixteen/...
```
I want to hide any reference that this WordPress theme is coming from Twenty Sixteen and customize the directory to something else:
```
http://example.com/wp-content/themes/my-site/...
```
While I can FTP to my website and rename the folder manually, I noticed that the theme does not receive any updates that are made on WordPress' repo.
I'd assume I would create a [child theme](https://codex.wordpress.org/Child_Themes) referring to Twenty Sixteen in order to still receive the latest updates for the theme and still have a custom directory name. Is that the best route?
|
changing the theme folder I guess it won't affect on updates but changing it's name do.
So like you said the best way that every professional company advice is to create a child-theme and modify everything you want on it.
|
249,077 |
<pre><code><?php
/*
* Plugin Name: Official Treehouse Badges Plugin
* Plugin URI: http://wptreehouse.com/wptreehouse-badges-plugin/
* Description: Provides both widgets and shortcodes to help you display your Treehouse profile badges on your website. The official Treehouse badges plugin.
* Version: 1.0
* Author: Editorial Staff
* Author URI: http://wp.zacgordon.com
* License: GPL2
*
*/
/*---------------------------------------*/
/* 1. ASSIGN GLOBAL VARIABLE */
/*---------------------------------------*/
/*---------------------------------------*/
/* 2. PLUGIN ADMIN MENU */
/*---------------------------------------*/
function basic_treehouse_badges_menu() {
/*
* Use the add_options_page function
* add_options_page( $page_title, $menu_title, $capability, $menu-slug, $function )
*
*/
add_options_page(
'Official Tree House Badges Plugin',
'Treehouse Badges',
'manage options',
'wp-treehouse-badges',
'wptreehouse_badges_option_page'
);
}
add_action('admin_menu','basic_treehouse_badges_menu');
function wptreehouse_badges_option_page() {
if( !current_user_can ('manage_options')) {
wp_die('You do not have sufficient permission to acces this page.');
}
echo '<p> welcome to our plugin page </p>';
}
?>
</code></pre>
<p>I am just a beginner and have written a very simple basic plugin structure.</p>
<p>What's the mistake that's causing the "Treehouse Badges" menu name not to appear under the Settings menu in the admin section of WordPress.</p>
|
[
{
"answer_id": 249078,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>The only issue was that the capability was specified incorrectly when using <code>add_options_page()</code>. The capability should be <code>manage_options</code>. Note the underscore, no space:</p>\n\n<pre><code>function basic_treehouse_badges_menu() {\n /*\n * Use the add_options_page function\n * add_options_page( $page_title, $menu_title, $capability, $menu-slug, $function )\n *\n */\n add_options_page(\n 'Official Tree House Badges Plugin',\n 'Treehouse Badges',\n 'manage_options',\n 'wp-treehouse-badges',\n 'wptreehouse_badges_option_page'\n );\n}\nadd_action('admin_menu','basic_treehouse_badges_menu');\n\nfunction wptreehouse_badges_option_page() {\n if( !current_user_can ('manage_options')) {\n wp_die('You do not have sufficient permission to acces this page.');\n }\n echo '<p> welcome to our plugin page </p>';\n} \n</code></pre>\n"
},
{
"answer_id": 249079,
"author": "fmeaddons",
"author_id": 107871,
"author_profile": "https://wordpress.stackexchange.com/users/107871",
"pm_score": 2,
"selected": false,
"text": "<p>There is mistake in your code you use '<strong>manage options</strong>' instead of '<strong>manage_options</strong>'</p>\n\n<p>so correct code is</p>\n\n<pre><code>add_options_page(\n 'Official Tree House Badges Plugin',\n 'Treehouse Badges',\n 'manage_options',\n 'wp-treehouse-badges',\n 'wptreehouse_badges_option_page'\n );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Administration_Menus\" rel=\"nofollow noreferrer\">Here</a> you can read more about administration menu.</p>\n"
}
] |
2016/12/13
|
[
"https://wordpress.stackexchange.com/questions/249077",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
] |
```
<?php
/*
* Plugin Name: Official Treehouse Badges Plugin
* Plugin URI: http://wptreehouse.com/wptreehouse-badges-plugin/
* Description: Provides both widgets and shortcodes to help you display your Treehouse profile badges on your website. The official Treehouse badges plugin.
* Version: 1.0
* Author: Editorial Staff
* Author URI: http://wp.zacgordon.com
* License: GPL2
*
*/
/*---------------------------------------*/
/* 1. ASSIGN GLOBAL VARIABLE */
/*---------------------------------------*/
/*---------------------------------------*/
/* 2. PLUGIN ADMIN MENU */
/*---------------------------------------*/
function basic_treehouse_badges_menu() {
/*
* Use the add_options_page function
* add_options_page( $page_title, $menu_title, $capability, $menu-slug, $function )
*
*/
add_options_page(
'Official Tree House Badges Plugin',
'Treehouse Badges',
'manage options',
'wp-treehouse-badges',
'wptreehouse_badges_option_page'
);
}
add_action('admin_menu','basic_treehouse_badges_menu');
function wptreehouse_badges_option_page() {
if( !current_user_can ('manage_options')) {
wp_die('You do not have sufficient permission to acces this page.');
}
echo '<p> welcome to our plugin page </p>';
}
?>
```
I am just a beginner and have written a very simple basic plugin structure.
What's the mistake that's causing the "Treehouse Badges" menu name not to appear under the Settings menu in the admin section of WordPress.
|
The only issue was that the capability was specified incorrectly when using `add_options_page()`. The capability should be `manage_options`. Note the underscore, no space:
```
function basic_treehouse_badges_menu() {
/*
* Use the add_options_page function
* add_options_page( $page_title, $menu_title, $capability, $menu-slug, $function )
*
*/
add_options_page(
'Official Tree House Badges Plugin',
'Treehouse Badges',
'manage_options',
'wp-treehouse-badges',
'wptreehouse_badges_option_page'
);
}
add_action('admin_menu','basic_treehouse_badges_menu');
function wptreehouse_badges_option_page() {
if( !current_user_can ('manage_options')) {
wp_die('You do not have sufficient permission to acces this page.');
}
echo '<p> welcome to our plugin page </p>';
}
```
|
249,082 |
<p>I am trying to manually add a new plugin to WordPress site (I need to add a customized plugin).</p>
<p>I do it by:</p>
<ol>
<li><p>uploading it via Ftp server (with FTPS connection) to <code>/var/www/html/wp-content/plugins</code></p></li>
<li><p>Copy/paste to <code>/var/www/html/wp-content/plugins</code></p></li>
</ol>
<p>But, I am not able to see it on WordPress site under plugin section.</p>
<p>I am using:</p>
<ol>
<li>WordPress 4.7</li>
<li>Filezilla (FTP client) and VSFTPD (Ubuntu FTP server).</li>
<li>Ubuntu 16.10</li>
</ol>
<p>Any ideas as to what the issue is?</p>
|
[
{
"answer_id": 249078,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>The only issue was that the capability was specified incorrectly when using <code>add_options_page()</code>. The capability should be <code>manage_options</code>. Note the underscore, no space:</p>\n\n<pre><code>function basic_treehouse_badges_menu() {\n /*\n * Use the add_options_page function\n * add_options_page( $page_title, $menu_title, $capability, $menu-slug, $function )\n *\n */\n add_options_page(\n 'Official Tree House Badges Plugin',\n 'Treehouse Badges',\n 'manage_options',\n 'wp-treehouse-badges',\n 'wptreehouse_badges_option_page'\n );\n}\nadd_action('admin_menu','basic_treehouse_badges_menu');\n\nfunction wptreehouse_badges_option_page() {\n if( !current_user_can ('manage_options')) {\n wp_die('You do not have sufficient permission to acces this page.');\n }\n echo '<p> welcome to our plugin page </p>';\n} \n</code></pre>\n"
},
{
"answer_id": 249079,
"author": "fmeaddons",
"author_id": 107871,
"author_profile": "https://wordpress.stackexchange.com/users/107871",
"pm_score": 2,
"selected": false,
"text": "<p>There is mistake in your code you use '<strong>manage options</strong>' instead of '<strong>manage_options</strong>'</p>\n\n<p>so correct code is</p>\n\n<pre><code>add_options_page(\n 'Official Tree House Badges Plugin',\n 'Treehouse Badges',\n 'manage_options',\n 'wp-treehouse-badges',\n 'wptreehouse_badges_option_page'\n );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Administration_Menus\" rel=\"nofollow noreferrer\">Here</a> you can read more about administration menu.</p>\n"
}
] |
2016/12/13
|
[
"https://wordpress.stackexchange.com/questions/249082",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107436/"
] |
I am trying to manually add a new plugin to WordPress site (I need to add a customized plugin).
I do it by:
1. uploading it via Ftp server (with FTPS connection) to `/var/www/html/wp-content/plugins`
2. Copy/paste to `/var/www/html/wp-content/plugins`
But, I am not able to see it on WordPress site under plugin section.
I am using:
1. WordPress 4.7
2. Filezilla (FTP client) and VSFTPD (Ubuntu FTP server).
3. Ubuntu 16.10
Any ideas as to what the issue is?
|
The only issue was that the capability was specified incorrectly when using `add_options_page()`. The capability should be `manage_options`. Note the underscore, no space:
```
function basic_treehouse_badges_menu() {
/*
* Use the add_options_page function
* add_options_page( $page_title, $menu_title, $capability, $menu-slug, $function )
*
*/
add_options_page(
'Official Tree House Badges Plugin',
'Treehouse Badges',
'manage_options',
'wp-treehouse-badges',
'wptreehouse_badges_option_page'
);
}
add_action('admin_menu','basic_treehouse_badges_menu');
function wptreehouse_badges_option_page() {
if( !current_user_can ('manage_options')) {
wp_die('You do not have sufficient permission to acces this page.');
}
echo '<p> welcome to our plugin page </p>';
}
```
|
249,109 |
<p>Is there a way to hide user profiles in the front end, while still allowing their information to be accessible in the backend?</p>
<p>Something similar to setting posts or pages to "draft" but for users would function perfectly. Is there a way to do this?</p>
|
[
{
"answer_id": 249204,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": false,
"text": "<p>The database table for users holds the <code>user_status</code> as integer:</p>\n\n<pre><code> $users_single_table = \"CREATE TABLE $wpdb->users (\n ID bigint(20) unsigned NOT NULL auto_increment,\n user_login varchar(60) NOT NULL default '',\n user_pass varchar(255) NOT NULL default '',\n user_nicename varchar(50) NOT NULL default '',\n user_email varchar(100) NOT NULL default '',\n user_url varchar(100) NOT NULL default '',\n user_registered datetime NOT NULL default '0000-00-00 00:00:00',\n user_activation_key varchar(255) NOT NULL default '',\n user_status int(11) NOT NULL default '0',\n display_name varchar(250) NOT NULL default '',\n PRIMARY KEY (ID),\n KEY user_login_key (user_login),\n KEY user_nicename (user_nicename),\n KEY user_email (user_email)\n) $charset_collate;\\n\";\n</code></pre>\n\n<p>The <code>WP_Users</code> class at the moment doesn't have anything that would alter the state property, nor even hold that property. </p>\n\n<p><a href=\"https://i.stack.imgur.com/ta8H2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ta8H2.png\" alt=\"enter image description here\"></a></p>\n\n<p>There is one function inside <code>wp-admin/includes/ms.php</code> that may show you the path how to go.</p>\n\n<pre><code>update_user_status( $user_id, 'spam', '1' );\n</code></pre>\n\n<p>but loads only for multisite:</p>\n\n<pre><code>/wp-admin/includes/admin.php:\n82 if ( is_multisite() ) {\n83 require_once(ABSPATH . 'wp-admin/includes/ms-admin-filters.php');\n84: require_once(ABSPATH . 'wp-admin/includes/ms.php');\n85 require_once(ABSPATH . 'wp-admin/includes/ms-deprecated.php');\n86 }\n</code></pre>\n\n<p>It looks like this:</p>\n\n<pre><code>function update_user_status( $id, $pref, $value, $deprecated = null ) {\n global $wpdb;\n\n if ( null !== $deprecated )\n _deprecated_argument( __FUNCTION__, '3.0.2' );\n\n $wpdb->update( $wpdb->users, array( sanitize_key( $pref ) => $value ), array( 'ID' => $id ) );\n\n $user = new WP_User( $id );\n clean_user_cache( $user );\n\n if ( $pref == 'spam' ) {\n if ( $value == 1 ) {\n /**\n * Fires after the user is marked as a SPAM user.\n *\n * @since 3.0.0\n *\n * @param int $id ID of the user marked as SPAM.\n */\n do_action( 'make_spam_user', $id );\n } else {\n /**\n * Fires after the user is marked as a HAM user. Opposite of SPAM.\n *\n * @since 3.0.0\n *\n * @param int $id ID of the user marked as HAM.\n */\n do_action( 'make_ham_user', $id );\n }\n }\n\n return $value;\n}\n</code></pre>\n\n<p>You could use something similar and create <strong>the action hook</strong> <code>make_draft_user</code>, probable in your function <code>_20161214_update_user_status( $user_id, 'draft', '1' );</code></p>\n\n<p>Inside your very own <code>make_draft_user</code> hook you could define what to do.</p>\n\n<blockquote>\n <p>So WordPress out of the box doesn't provide draft users. Maybe it will one day with the clear use case scenario. Maybe the status will be a string, and not the int (This is the case for posts).</p>\n</blockquote>\n"
},
{
"answer_id": 249344,
"author": "NNCCBB",
"author_id": 108864,
"author_profile": "https://wordpress.stackexchange.com/users/108864",
"pm_score": 0,
"selected": false,
"text": "<p>Setting user_status to 2 in the database appears to do the trick</p>\n"
}
] |
2016/12/13
|
[
"https://wordpress.stackexchange.com/questions/249109",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108864/"
] |
Is there a way to hide user profiles in the front end, while still allowing their information to be accessible in the backend?
Something similar to setting posts or pages to "draft" but for users would function perfectly. Is there a way to do this?
|
The database table for users holds the `user_status` as integer:
```
$users_single_table = "CREATE TABLE $wpdb->users (
ID bigint(20) unsigned NOT NULL auto_increment,
user_login varchar(60) NOT NULL default '',
user_pass varchar(255) NOT NULL default '',
user_nicename varchar(50) NOT NULL default '',
user_email varchar(100) NOT NULL default '',
user_url varchar(100) NOT NULL default '',
user_registered datetime NOT NULL default '0000-00-00 00:00:00',
user_activation_key varchar(255) NOT NULL default '',
user_status int(11) NOT NULL default '0',
display_name varchar(250) NOT NULL default '',
PRIMARY KEY (ID),
KEY user_login_key (user_login),
KEY user_nicename (user_nicename),
KEY user_email (user_email)
) $charset_collate;\n";
```
The `WP_Users` class at the moment doesn't have anything that would alter the state property, nor even hold that property.
[](https://i.stack.imgur.com/ta8H2.png)
There is one function inside `wp-admin/includes/ms.php` that may show you the path how to go.
```
update_user_status( $user_id, 'spam', '1' );
```
but loads only for multisite:
```
/wp-admin/includes/admin.php:
82 if ( is_multisite() ) {
83 require_once(ABSPATH . 'wp-admin/includes/ms-admin-filters.php');
84: require_once(ABSPATH . 'wp-admin/includes/ms.php');
85 require_once(ABSPATH . 'wp-admin/includes/ms-deprecated.php');
86 }
```
It looks like this:
```
function update_user_status( $id, $pref, $value, $deprecated = null ) {
global $wpdb;
if ( null !== $deprecated )
_deprecated_argument( __FUNCTION__, '3.0.2' );
$wpdb->update( $wpdb->users, array( sanitize_key( $pref ) => $value ), array( 'ID' => $id ) );
$user = new WP_User( $id );
clean_user_cache( $user );
if ( $pref == 'spam' ) {
if ( $value == 1 ) {
/**
* Fires after the user is marked as a SPAM user.
*
* @since 3.0.0
*
* @param int $id ID of the user marked as SPAM.
*/
do_action( 'make_spam_user', $id );
} else {
/**
* Fires after the user is marked as a HAM user. Opposite of SPAM.
*
* @since 3.0.0
*
* @param int $id ID of the user marked as HAM.
*/
do_action( 'make_ham_user', $id );
}
}
return $value;
}
```
You could use something similar and create **the action hook** `make_draft_user`, probable in your function `_20161214_update_user_status( $user_id, 'draft', '1' );`
Inside your very own `make_draft_user` hook you could define what to do.
>
> So WordPress out of the box doesn't provide draft users. Maybe it will one day with the clear use case scenario. Maybe the status will be a string, and not the int (This is the case for posts).
>
>
>
|
249,115 |
<p>I want to show author avatar in post info. So I use</p>
<pre><code><?php echo get_avatar( get_the_author_meta( 'ID' ) , 80); ?>
</code></pre>
<p>But how can I check if user has avatar? </p>
|
[
{
"answer_id": 249117,
"author": "Oreo",
"author_id": 108862,
"author_profile": "https://wordpress.stackexchange.com/users/108862",
"pm_score": 1,
"selected": false,
"text": "<p><code>get_avatar()</code> returns An img element for the user's avatar or false on failure. The function does not output anything; you have to echo the return value.</p>\n\n<p>so you can try something like that</p>\n\n<pre><code>if( get_avatar( get_the_author_meta( 'ID' ) ) == 0) {\n // no img code\n} else {\n echo get_avatar( get_the_author_meta( 'ID' ) , 80 );\n}\n</code></pre>\n"
},
{
"answer_id": 346077,
"author": "RFerreira",
"author_id": 160088,
"author_profile": "https://wordpress.stackexchange.com/users/160088",
"pm_score": -1,
"selected": false,
"text": "<p>this should do what you need:</p>\n<pre><code>if( get_avatar( get_the_author_meta( 'ID' ) ) ){\n echo get_avatar( get_the_author_meta( 'ID' ) , '64' );\n}else{\n echo '<img alt="no-image" src="https://image.flaticon.com/icons/svg/149/149071.svg" class="avatar avatar-64 photo" height="64" width="64">';\n}\n</code></pre>\n"
}
] |
2016/12/13
|
[
"https://wordpress.stackexchange.com/questions/249115",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103556/"
] |
I want to show author avatar in post info. So I use
```
<?php echo get_avatar( get_the_author_meta( 'ID' ) , 80); ?>
```
But how can I check if user has avatar?
|
`get_avatar()` returns An img element for the user's avatar or false on failure. The function does not output anything; you have to echo the return value.
so you can try something like that
```
if( get_avatar( get_the_author_meta( 'ID' ) ) == 0) {
// no img code
} else {
echo get_avatar( get_the_author_meta( 'ID' ) , 80 );
}
```
|
249,190 |
<p>I have put this code on author.php page</p>
<pre><code> <?php if ( have_posts() ) : while ( have_posts() ) : the_post();
//gets the number of comment(s) on a post
$comments_number = get_comments_number();
//adds all the comment counts up
$numbercomment += $comments_number;
?>
<?php endwhile; ?>
<span>A total of <?php echo $numbercomment; ?> comments have been made on this author posts.</span>
</code></pre>
<p>Currently i am using a loop to find number of a comments on a post and total it with all the other comment count on other posts. The consists of only the author's post so in that way i can find the number of comments people have made on that specific author's posts.
Is there a simpler way of doing it.</p>
<p>EDIT:<br>
I want to count the total number of comments people have made on all of that author's posts.
Put the above code up in author.php file and you will get what i mean..</p>
|
[
{
"answer_id": 249196,
"author": "Pim",
"author_id": 50432,
"author_profile": "https://wordpress.stackexchange.com/users/50432",
"pm_score": 3,
"selected": true,
"text": "<p>You could use <code>get_comments()</code>, this way you don't have to loop through posts.</p>\n\n<pre><code><?php\n $args = array(\n 'post_author' => '' // fill in post author ID\n );\n\n $author_comments = get_comments($args);\n\n echo count($author_comments);\n\n?>\n</code></pre>\n"
},
{
"answer_id": 249197,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": false,
"text": "<p>Here I've written a SQL based function for you-</p>\n\n<pre><code>function the_dramatist_count_user_comments( $args = array() ) {\n global $wpdb;\n $default_args = array(\n 'author_id' => 1,\n 'approved' => 1\n );\n $param = wp_parse_args( $args, $default_args );\n $sql = $wpdb->prepare( \"SELECT COUNT(comments.comment_ID) \n FROM {$wpdb->comments} AS comments \n LEFT JOIN {$wpdb->posts} AS posts\n ON comments.comment_post_ID = posts.ID\n WHERE posts.post_author = %d\n AND comment_approved = %d\n AND comment_type IN ('comment', '')\",\n $param\n );\n\n return $wpdb->get_var( $sql );\n}\n</code></pre>\n\n<p>Use it like below-</p>\n\n<pre><code>$author_posts_comments_count = the_dramatist_count_user_comments(\n array(\n 'author_id' => 1, // Author ID\n 'approved' => 1, // Approved or not Approved\n )\n);\n</code></pre>\n\n<p>Now on <code>$author_posts_comments_count</code> you'll get the full comments count for an authors all posts.</p>\n\n<blockquote>\n <p>It's tested.</p>\n</blockquote>\n\n<p>Hope that helps.</p>\n"
}
] |
2016/12/14
|
[
"https://wordpress.stackexchange.com/questions/249190",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75425/"
] |
I have put this code on author.php page
```
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
//gets the number of comment(s) on a post
$comments_number = get_comments_number();
//adds all the comment counts up
$numbercomment += $comments_number;
?>
<?php endwhile; ?>
<span>A total of <?php echo $numbercomment; ?> comments have been made on this author posts.</span>
```
Currently i am using a loop to find number of a comments on a post and total it with all the other comment count on other posts. The consists of only the author's post so in that way i can find the number of comments people have made on that specific author's posts.
Is there a simpler way of doing it.
EDIT:
I want to count the total number of comments people have made on all of that author's posts.
Put the above code up in author.php file and you will get what i mean..
|
You could use `get_comments()`, this way you don't have to loop through posts.
```
<?php
$args = array(
'post_author' => '' // fill in post author ID
);
$author_comments = get_comments($args);
echo count($author_comments);
?>
```
|
249,202 |
<p>Is it possible to order a tag page by the 'most commonly used' tag? </p>
<p>For example:</p>
<p>Say I have three tags: Apple, Orange, Banana, and 100 posts. </p>
<p>90 of those posts are tagged Apple, 50 are tagged Orange, and 20 are tagged Banana. (Some are tagged with more than 1 tag.) </p>
<p>So I want to order the posts listed on the tags page by Apple Tags first.</p>
<p>Right now, I am ordering by last modified using the following query, but would like to order by the tag that is used the most across all posts.</p>
<pre><code> $args = array(
'posts_per_page' => 10, // Get 10 posts
'paged' => $paged,
'post_type' => 'post',
'tag' => $tag->slug,
'orderby' => 'modified'
);
</code></pre>
|
[
{
"answer_id": 249338,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": true,
"text": "<p>I'm afraid <code>orderby</code> taxonomy terms post count is not possible by <code>WP_Query</code>. <a href=\"https://wordpress.stackexchange.com/questions/14306/using-wp-query-is-it-possible-to-orderby-taxonomy/14309#14309\">See this answer</a>. So here I've written a SQL based function for you. It'll order your posts based on terms post count.</p>\n\n<pre><code>function the_dramatist_order_posts_by_tag_count( $args = '' ) {\n global $wpdb;\n $param = empty($args) ? 'post_tag' : $args;\n $sql = $wpdb->prepare(\"SELECT posts.*, terms.name AS tag, count \n FROM {$wpdb->posts} AS posts\n LEFT JOIN {$wpdb->term_relationships} AS t_rel\n ON (t_rel.object_id = posts.ID)\n LEFT JOIN {$wpdb->term_taxonomy} AS t_tax\n ON (t_rel.term_taxonomy_id = t_tax.term_taxonomy_id)\n LEFT JOIN {$wpdb->terms} AS terms\n ON (terms.term_id = t_tax.term_id)\n WHERE taxonomy LIKE '%s'\n ORDER BY t_tax.count DESC, terms.name\",\n array( $param )\n );\n\n return $wpdb->get_results($sql);\n}\n</code></pre>\n\n<p>It'll return you all the data from you posts table with <code>post_tag</code> term name and this terms post count. But it has a simple limitation and that is if you have one tag in multiple posts then the post will appear multiple time for each <code>post_tag</code> term it is attached to. You can use <code>GROUP BY posts.ID</code> to remove the duplicate posts, but it'll not give you all the terms and terms count. So with <code>GROUP BY posts.ID</code> the function will be like below-</p>\n\n<pre><code>function the_dramatist_order_posts_by_tag_count( $args = '' ) {\n global $wpdb;\n $param = empty($args) ? 'post_tag' : $args;\n $sql = $wpdb->prepare(\"SELECT posts.*, terms.name AS tag, count \n FROM {$wpdb->posts} AS posts\n LEFT JOIN {$wpdb->term_relationships} AS t_rel\n ON (t_rel.object_id = posts.ID)\n LEFT JOIN {$wpdb->term_taxonomy} AS t_tax\n ON (t_rel.term_taxonomy_id = t_tax.term_taxonomy_id)\n LEFT JOIN {$wpdb->terms} AS terms\n ON (terms.term_id = t_tax.term_id)\n WHERE taxonomy LIKE '%s'\n GROUP BY posts.ID\n ORDER BY t_tax.count DESC, terms.name\",\n array( $param )\n );\n return $wpdb->get_results($sql);\n}\n</code></pre>\n\n<p>Use which suits your need better.</p>\n\n<p>This function works on <code>post_tag</code> taxonomy by default. If you want to use it with other taxonomy just pass it as parameter like <code>the_dramatist_order_posts_by_tag_count( 'category' )</code></p>\n\n<p>Better you do a <code>print_r</code> on this function before using it in production to understand the data structure.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 284093,
"author": "VINICIUS HENRIQUE MAGALHAES",
"author_id": 130365,
"author_profile": "https://wordpress.stackexchange.com/users/130365",
"pm_score": 2,
"selected": false,
"text": "<p>This simple code make what you are looking for.</p>\n\n<pre><code>$tags = get_tags( array('orderby' => 'count', 'order' => 'DESC') );\n\nforeach ( (array) $tags as $tag ) {\n echo '<li><a href=\"' . get_tag_link ($tag->term_id) . '\" rel=\"tag\">' . $tag->name . ' (' . $tag->count . ') </a></li>';\n}\n</code></pre>\n"
}
] |
2016/12/14
|
[
"https://wordpress.stackexchange.com/questions/249202",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44848/"
] |
Is it possible to order a tag page by the 'most commonly used' tag?
For example:
Say I have three tags: Apple, Orange, Banana, and 100 posts.
90 of those posts are tagged Apple, 50 are tagged Orange, and 20 are tagged Banana. (Some are tagged with more than 1 tag.)
So I want to order the posts listed on the tags page by Apple Tags first.
Right now, I am ordering by last modified using the following query, but would like to order by the tag that is used the most across all posts.
```
$args = array(
'posts_per_page' => 10, // Get 10 posts
'paged' => $paged,
'post_type' => 'post',
'tag' => $tag->slug,
'orderby' => 'modified'
);
```
|
I'm afraid `orderby` taxonomy terms post count is not possible by `WP_Query`. [See this answer](https://wordpress.stackexchange.com/questions/14306/using-wp-query-is-it-possible-to-orderby-taxonomy/14309#14309). So here I've written a SQL based function for you. It'll order your posts based on terms post count.
```
function the_dramatist_order_posts_by_tag_count( $args = '' ) {
global $wpdb;
$param = empty($args) ? 'post_tag' : $args;
$sql = $wpdb->prepare("SELECT posts.*, terms.name AS tag, count
FROM {$wpdb->posts} AS posts
LEFT JOIN {$wpdb->term_relationships} AS t_rel
ON (t_rel.object_id = posts.ID)
LEFT JOIN {$wpdb->term_taxonomy} AS t_tax
ON (t_rel.term_taxonomy_id = t_tax.term_taxonomy_id)
LEFT JOIN {$wpdb->terms} AS terms
ON (terms.term_id = t_tax.term_id)
WHERE taxonomy LIKE '%s'
ORDER BY t_tax.count DESC, terms.name",
array( $param )
);
return $wpdb->get_results($sql);
}
```
It'll return you all the data from you posts table with `post_tag` term name and this terms post count. But it has a simple limitation and that is if you have one tag in multiple posts then the post will appear multiple time for each `post_tag` term it is attached to. You can use `GROUP BY posts.ID` to remove the duplicate posts, but it'll not give you all the terms and terms count. So with `GROUP BY posts.ID` the function will be like below-
```
function the_dramatist_order_posts_by_tag_count( $args = '' ) {
global $wpdb;
$param = empty($args) ? 'post_tag' : $args;
$sql = $wpdb->prepare("SELECT posts.*, terms.name AS tag, count
FROM {$wpdb->posts} AS posts
LEFT JOIN {$wpdb->term_relationships} AS t_rel
ON (t_rel.object_id = posts.ID)
LEFT JOIN {$wpdb->term_taxonomy} AS t_tax
ON (t_rel.term_taxonomy_id = t_tax.term_taxonomy_id)
LEFT JOIN {$wpdb->terms} AS terms
ON (terms.term_id = t_tax.term_id)
WHERE taxonomy LIKE '%s'
GROUP BY posts.ID
ORDER BY t_tax.count DESC, terms.name",
array( $param )
);
return $wpdb->get_results($sql);
}
```
Use which suits your need better.
This function works on `post_tag` taxonomy by default. If you want to use it with other taxonomy just pass it as parameter like `the_dramatist_order_posts_by_tag_count( 'category' )`
Better you do a `print_r` on this function before using it in production to understand the data structure.
Hope that helps.
|
249,214 |
<p>I have a piece of code displaying a list of sites in my multisite, and I want to exclude the archived ones:</p>
<pre><code>$mySites = ( wp_get_sites( $args ) );
foreach ( $mySites as $blog ) {
if ( ! ( is_archived($blog) ) ) {
switch_to_blog( $blog['blog_id'] );
printf( '%s<a href="%s">%s</a></li>' . "\r\n", $TagLi, home_url(), get_option( 'blogname' ) );
restore_current_blog();
}
}
</code></pre>
<p>Before updating to 4.7, this was working correctly. Now, it doesn't exclude archived sites anymore, it prints out a complete list. </p>
<p>Has the function <code>is_archived()</code> changed? Or what can the problem be?</p>
|
[
{
"answer_id": 249222,
"author": "Emil",
"author_id": 80532,
"author_profile": "https://wordpress.stackexchange.com/users/80532",
"pm_score": 3,
"selected": true,
"text": "<p>Can you try out the following code somewhere and post the output?</p>\n\n<pre><code>$mySites = wp_get_sites($args);\nforeach ($mySites as $blog){\n print_r(get_blog_status($blog['blog_id'], 'archived'));\n}\n</code></pre>\n\n<p>If this works, I suspect the code behind <code>is_archived()</code> used to understand blog-objects, but the <a href=\"https://developer.wordpress.org/reference/functions/is_archived/\" rel=\"nofollow noreferrer\">function is supposed to recieve only the blog ID</a>, not the whole object.</p>\n\n<p>Your code should be the following:</p>\n\n<pre><code>$mySites = wp_get_sites($args);\nforeach ($mySites as $blog){\n if (!is_archived($blog['blog_id'])){\n switch_to_blog( $blog['blog_id'] );\n printf( '%s<a href=\"%s\">%s</a></li>' . \"\\r\\n\", $TagLi, home_url(), get_option( 'blogname' ) ); \n\n restore_current_blog();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 249225,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>Note that <code>get_sites()</code> has a different output than the deprecated <code>wp_get_sites()</code> function in WordPress 4.7+.</p>\n\n<p>The <code>get_sites()</code> function returns an array of <code>WP_Site</code> objects, but <code>wp_get_sites()</code> returns an array of arrays.</p>\n\n<p>So if you use <code>get_sites()</code>, you need to adjust your code snippet with:</p>\n\n<pre><code>is_archived( $blog->blog_id )\n</code></pre>\n\n<p>and </p>\n\n<pre><code>switch_to_blog( $blog->blog_id );\n</code></pre>\n\n<p>instead of using <code>$blog['blog_id']</code>.</p>\n"
}
] |
2016/12/14
|
[
"https://wordpress.stackexchange.com/questions/249214",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78708/"
] |
I have a piece of code displaying a list of sites in my multisite, and I want to exclude the archived ones:
```
$mySites = ( wp_get_sites( $args ) );
foreach ( $mySites as $blog ) {
if ( ! ( is_archived($blog) ) ) {
switch_to_blog( $blog['blog_id'] );
printf( '%s<a href="%s">%s</a></li>' . "\r\n", $TagLi, home_url(), get_option( 'blogname' ) );
restore_current_blog();
}
}
```
Before updating to 4.7, this was working correctly. Now, it doesn't exclude archived sites anymore, it prints out a complete list.
Has the function `is_archived()` changed? Or what can the problem be?
|
Can you try out the following code somewhere and post the output?
```
$mySites = wp_get_sites($args);
foreach ($mySites as $blog){
print_r(get_blog_status($blog['blog_id'], 'archived'));
}
```
If this works, I suspect the code behind `is_archived()` used to understand blog-objects, but the [function is supposed to recieve only the blog ID](https://developer.wordpress.org/reference/functions/is_archived/), not the whole object.
Your code should be the following:
```
$mySites = wp_get_sites($args);
foreach ($mySites as $blog){
if (!is_archived($blog['blog_id'])){
switch_to_blog( $blog['blog_id'] );
printf( '%s<a href="%s">%s</a></li>' . "\r\n", $TagLi, home_url(), get_option( 'blogname' ) );
restore_current_blog();
}
}
```
|
249,218 |
<p>WordPress has several APIs build in:</p>
<ul>
<li><a href="https://codex.wordpress.org/XML-RPC_WordPress_API" rel="noreferrer">XML-RPC</a></li>
<li><a href="http://v2.wp-api.org/" rel="noreferrer">REST API</a></li>
</ul>
<p>by default they don't return custom post types or protected meta keys.</p>
<p>I want to access the protected meta fields of a plugin. I tried to follow the examples given <a href="https://journal.rmccue.io/351/the-complex-state-of-meta-in-the-wordpress-rest-api/" rel="noreferrer">here</a> and <a href="https://developer.wordpress.org/rest-api/adding-rest-api-support-for-custom-content-types/" rel="noreferrer">here</a>.</p>
<p>I did manage that the wp-json API would return custom post types by adding this code:</p>
<pre><code>/**
* Add REST API support to an already registered post type.
*/
add_action( 'init', 'my_custom_post_type_rest_support', 25 );
function my_custom_post_type_rest_support() {
global $wp_post_types;
// be sure to set this to the name of your post type!
$post_type_name = 'tribe_venue';
if( isset( $wp_post_types[ $post_type_name ] ) ) {
$wp_post_types[$post_type_name]->show_in_rest = true;
$wp_post_types[$post_type_name]->rest_base = $post_type_name;
$wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
}
$post_type_name2 = 'tribe_events';
if( isset( $wp_post_types[ $post_type_name2 ] ) ) {
$wp_post_types[$post_type_name2]->show_in_rest = true;
$wp_post_types[$post_type_name2]->rest_base = $post_type_name2;
$wp_post_types[$post_type_name2]->rest_controller_class = 'WP_REST_Posts_Controller';
}
}
</code></pre>
<p>But I was not able to include protected meta keys in the response.</p>
<p>I tried the following code:</p>
<pre><code>add_filter( 'is_protected_meta', function ( $protected, $key, $type ) {
if ( $type === 'tribe_venue' && $key === '_VenueVenue' ) {
return true;
}
return $protected;
}, 10, 3 );
add_filter( 'rae_include_protected_meta', '__return_true' );
</code></pre>
<p>and the following code:</p>
<pre><code>function custom_rest_api_allowed_public_metadata($allowed_meta_keys){
$allowed_meta_keys[] = '_VenueVenue';
$allowed_meta_keys[] = '_VenueAddress';
$allowed_meta_keys[] = '_VenueCity';
return $allowed_meta_keys;
}
add_filter( 'rest_api_allowed_public_metadata', 'custom_rest_api_allowed_public_metadata' );
</code></pre>
<p>but neither works.</p>
<p>Does anybody know what is needed so make such protected fields accessible through any of the APIs? Is there a working example anywhere? </p>
|
[
{
"answer_id": 263457,
"author": "J.C. Hiatt",
"author_id": 117545,
"author_profile": "https://wordpress.stackexchange.com/users/117545",
"pm_score": 0,
"selected": false,
"text": "<p>With the REST API, there's a <code>rest_query_vars</code> filter you can use:</p>\n\n<pre><code>function my_allow_meta_query( $valid_vars ) {\n\n $valid_vars = array_merge( $valid_vars, array( 'meta_key', 'meta_value') );\n\n return $valid_vars;\n}\n\nadd_filter( 'rest_query_vars', 'my_allow_meta_query' );\n</code></pre>\n\n<p>This allows you to use a route like this to query a meta field:</p>\n\n<p><code>wp-json/wp/v2/posts?filter[meta_key]=MY-KEY&filter[meta_value]=MY-VALUE</code></p>\n\n<p>There are also more complex ways you can do it. Check out the source link below.</p>\n\n<p>Source: <a href=\"https://1fix.io/blog/2015/07/20/query-vars-wp-api/\" rel=\"nofollow noreferrer\">https://1fix.io/blog/2015/07/20/query-vars-wp-api/</a></p>\n"
},
{
"answer_id": 284541,
"author": "Levi Dulstein",
"author_id": 101988,
"author_profile": "https://wordpress.stackexchange.com/users/101988",
"pm_score": 1,
"selected": false,
"text": "<p>To me, the simplest solution would be creating additional field in JSON response and populating it with selected post meta:</p>\n\n<pre><code>function create_api_posts_meta_field() {\n\n // \"tribe_venue\" is your post type name, \n // \"protected-fields\" is a name for new JSON field\n\n register_rest_field( 'tribe_venue', 'protected-fields', [\n 'get_callback' => 'get_post_meta_for_api',\n 'schema' => null,\n ] );\n}\n\nadd_action( 'rest_api_init', 'create_api_posts_meta_field' );\n\n/**\n * Callback function to populate our JSON field\n */\nfunction get_post_meta_for_api( $object ) {\n\n $meta = get_post_meta( $object['id'] );\n\n return [\n 'venue' => $meta['_VenueVenue'] ?: '',\n 'address' => $meta['_VenueAddress'] ?: '',\n 'city' => $meta['_VenueCity'] ?: '',\n ];\n}\n</code></pre>\n\n<p>You should be able to see your meta data both in \n<code>/wp-json/wp/v2/tribe_venue/</code> and\n<code>/wp-json/wp/v2/tribe_venue/{POST_ID}</code></p>\n"
}
] |
2016/12/14
|
[
"https://wordpress.stackexchange.com/questions/249218",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80953/"
] |
WordPress has several APIs build in:
* [XML-RPC](https://codex.wordpress.org/XML-RPC_WordPress_API)
* [REST API](http://v2.wp-api.org/)
by default they don't return custom post types or protected meta keys.
I want to access the protected meta fields of a plugin. I tried to follow the examples given [here](https://journal.rmccue.io/351/the-complex-state-of-meta-in-the-wordpress-rest-api/) and [here](https://developer.wordpress.org/rest-api/adding-rest-api-support-for-custom-content-types/).
I did manage that the wp-json API would return custom post types by adding this code:
```
/**
* Add REST API support to an already registered post type.
*/
add_action( 'init', 'my_custom_post_type_rest_support', 25 );
function my_custom_post_type_rest_support() {
global $wp_post_types;
// be sure to set this to the name of your post type!
$post_type_name = 'tribe_venue';
if( isset( $wp_post_types[ $post_type_name ] ) ) {
$wp_post_types[$post_type_name]->show_in_rest = true;
$wp_post_types[$post_type_name]->rest_base = $post_type_name;
$wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
}
$post_type_name2 = 'tribe_events';
if( isset( $wp_post_types[ $post_type_name2 ] ) ) {
$wp_post_types[$post_type_name2]->show_in_rest = true;
$wp_post_types[$post_type_name2]->rest_base = $post_type_name2;
$wp_post_types[$post_type_name2]->rest_controller_class = 'WP_REST_Posts_Controller';
}
}
```
But I was not able to include protected meta keys in the response.
I tried the following code:
```
add_filter( 'is_protected_meta', function ( $protected, $key, $type ) {
if ( $type === 'tribe_venue' && $key === '_VenueVenue' ) {
return true;
}
return $protected;
}, 10, 3 );
add_filter( 'rae_include_protected_meta', '__return_true' );
```
and the following code:
```
function custom_rest_api_allowed_public_metadata($allowed_meta_keys){
$allowed_meta_keys[] = '_VenueVenue';
$allowed_meta_keys[] = '_VenueAddress';
$allowed_meta_keys[] = '_VenueCity';
return $allowed_meta_keys;
}
add_filter( 'rest_api_allowed_public_metadata', 'custom_rest_api_allowed_public_metadata' );
```
but neither works.
Does anybody know what is needed so make such protected fields accessible through any of the APIs? Is there a working example anywhere?
|
To me, the simplest solution would be creating additional field in JSON response and populating it with selected post meta:
```
function create_api_posts_meta_field() {
// "tribe_venue" is your post type name,
// "protected-fields" is a name for new JSON field
register_rest_field( 'tribe_venue', 'protected-fields', [
'get_callback' => 'get_post_meta_for_api',
'schema' => null,
] );
}
add_action( 'rest_api_init', 'create_api_posts_meta_field' );
/**
* Callback function to populate our JSON field
*/
function get_post_meta_for_api( $object ) {
$meta = get_post_meta( $object['id'] );
return [
'venue' => $meta['_VenueVenue'] ?: '',
'address' => $meta['_VenueAddress'] ?: '',
'city' => $meta['_VenueCity'] ?: '',
];
}
```
You should be able to see your meta data both in
`/wp-json/wp/v2/tribe_venue/` and
`/wp-json/wp/v2/tribe_venue/{POST_ID}`
|
249,221 |
<p>I was creating a custom plugin which was to send certain emails based on the content/category of a post, but whilst trying to do that, I ran into some problems just getting a basic email sent out. Am I hooking on to the wrong function here? When I publish a post, nothing happens.</p>
<pre><code><?php
/**
* Plugin Name: Conditional Emailing
* Description: Sends emails based on categories.
* Version: 1.0
* Author: Ceds
*/
add_action( 'new_to_publish', 'conditional_email', 10, 0);
function conditional_email() {
wp_mail('[email protected]','test','test');
}
?>
</code></pre>
<p>What am I doing wrong here?</p>
|
[
{
"answer_id": 249256,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 2,
"selected": true,
"text": "<p>You need to add parameters <code>$old_status</code> and <code>$new_status</code> to the function. </p>\n\n<pre><code> function conditional_email( $old_status, $new_status) {\n wp_mail('[email protected]','test','test');\n }\n</code></pre>\n\n<p>You will see that in the example <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Hope it works after !</p>\n"
},
{
"answer_id": 351830,
"author": "ocReaper",
"author_id": 146244,
"author_profile": "https://wordpress.stackexchange.com/users/146244",
"pm_score": 0,
"selected": false,
"text": "<p>The problem with your code is that you passed zero parameters, but the <a href=\"https://codex.wordpress.org/Post_Status_Transitions#.7Bold_status.7D_to_.7Bnew_status.7D_Hook\" rel=\"nofollow noreferrer\">documentation</a> clearly specifies that:</p>\n\n<blockquote>\n <p>It is necessary to specify the number of arguments <code>do_action()</code> should pass to the callback function.</p>\n</blockquote>\n\n<p>Also another nice thing to know: this hook does not run if you click on <code>new post</code>, type in the title and immediately hit the <code>publish</code> button. It only runs if you wait for WordPress to generate the URL for the post! It is because of a <code>DOING_AUTOSAVE</code> condition in the core function.</p>\n\n<p>So here is the corrected code for you:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'new_to_publish', 'conditional_email', 10, 1);\n\n/**\n * Send emails based on categories when a post is published\n *\n * @param \\WP_Post $post\n */\nfunction conditional_email( $post ) {\n wp_mail( '[email protected]', 'test', 'test' );\n}\n</code></pre>\n"
}
] |
2016/12/14
|
[
"https://wordpress.stackexchange.com/questions/249221",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103117/"
] |
I was creating a custom plugin which was to send certain emails based on the content/category of a post, but whilst trying to do that, I ran into some problems just getting a basic email sent out. Am I hooking on to the wrong function here? When I publish a post, nothing happens.
```
<?php
/**
* Plugin Name: Conditional Emailing
* Description: Sends emails based on categories.
* Version: 1.0
* Author: Ceds
*/
add_action( 'new_to_publish', 'conditional_email', 10, 0);
function conditional_email() {
wp_mail('[email protected]','test','test');
}
?>
```
What am I doing wrong here?
|
You need to add parameters `$old_status` and `$new_status` to the function.
```
function conditional_email( $old_status, $new_status) {
wp_mail('[email protected]','test','test');
}
```
You will see that in the example [here](https://codex.wordpress.org/Post_Status_Transitions)
Hope it works after !
|
249,233 |
<p>I need to organize the pages on my website so that they appear with the proper hierarchy. The problem is that the category-derived page is appearing outside my hierarchy. This is the current hierarchy if you are on my site today:</p>
<pre><code>Home mysite.com
-> Internal (page) mysite.com/internal
-> Docs (page) mysite.com/internal/docs
-> Policy (category) mysite.com/category/policy
</code></pre>
<p>I need the policy category page to appear under Internal, which is accessible only by my registered users, such as:</p>
<pre><code>Home mysite.com
-> Internal (page) mysite.com/internal
-> Docs (page) mysite.com/internal/docs
-> Policy (category) mysite.com/internal/policy
</code></pre>
<p>I have other (External/Public) category pages that need to be handed differently. Any ideas as to how I can make this happen would be much appreciated.</p>
|
[
{
"answer_id": 249256,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 2,
"selected": true,
"text": "<p>You need to add parameters <code>$old_status</code> and <code>$new_status</code> to the function. </p>\n\n<pre><code> function conditional_email( $old_status, $new_status) {\n wp_mail('[email protected]','test','test');\n }\n</code></pre>\n\n<p>You will see that in the example <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Hope it works after !</p>\n"
},
{
"answer_id": 351830,
"author": "ocReaper",
"author_id": 146244,
"author_profile": "https://wordpress.stackexchange.com/users/146244",
"pm_score": 0,
"selected": false,
"text": "<p>The problem with your code is that you passed zero parameters, but the <a href=\"https://codex.wordpress.org/Post_Status_Transitions#.7Bold_status.7D_to_.7Bnew_status.7D_Hook\" rel=\"nofollow noreferrer\">documentation</a> clearly specifies that:</p>\n\n<blockquote>\n <p>It is necessary to specify the number of arguments <code>do_action()</code> should pass to the callback function.</p>\n</blockquote>\n\n<p>Also another nice thing to know: this hook does not run if you click on <code>new post</code>, type in the title and immediately hit the <code>publish</code> button. It only runs if you wait for WordPress to generate the URL for the post! It is because of a <code>DOING_AUTOSAVE</code> condition in the core function.</p>\n\n<p>So here is the corrected code for you:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'new_to_publish', 'conditional_email', 10, 1);\n\n/**\n * Send emails based on categories when a post is published\n *\n * @param \\WP_Post $post\n */\nfunction conditional_email( $post ) {\n wp_mail( '[email protected]', 'test', 'test' );\n}\n</code></pre>\n"
}
] |
2016/12/14
|
[
"https://wordpress.stackexchange.com/questions/249233",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51855/"
] |
I need to organize the pages on my website so that they appear with the proper hierarchy. The problem is that the category-derived page is appearing outside my hierarchy. This is the current hierarchy if you are on my site today:
```
Home mysite.com
-> Internal (page) mysite.com/internal
-> Docs (page) mysite.com/internal/docs
-> Policy (category) mysite.com/category/policy
```
I need the policy category page to appear under Internal, which is accessible only by my registered users, such as:
```
Home mysite.com
-> Internal (page) mysite.com/internal
-> Docs (page) mysite.com/internal/docs
-> Policy (category) mysite.com/internal/policy
```
I have other (External/Public) category pages that need to be handed differently. Any ideas as to how I can make this happen would be much appreciated.
|
You need to add parameters `$old_status` and `$new_status` to the function.
```
function conditional_email( $old_status, $new_status) {
wp_mail('[email protected]','test','test');
}
```
You will see that in the example [here](https://codex.wordpress.org/Post_Status_Transitions)
Hope it works after !
|
249,237 |
<p>I'm using [feed to post RSS Aggregator] and get posts from 44 sites. main page loading is too slow. I checked GTmetrix and it seems good but I don't know how can I improve my website loading. <a href="http://akhbartop.ir/" rel="nofollow noreferrer">http://akhbartop.ir/</a></p>
|
[
{
"answer_id": 249256,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 2,
"selected": true,
"text": "<p>You need to add parameters <code>$old_status</code> and <code>$new_status</code> to the function. </p>\n\n<pre><code> function conditional_email( $old_status, $new_status) {\n wp_mail('[email protected]','test','test');\n }\n</code></pre>\n\n<p>You will see that in the example <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Hope it works after !</p>\n"
},
{
"answer_id": 351830,
"author": "ocReaper",
"author_id": 146244,
"author_profile": "https://wordpress.stackexchange.com/users/146244",
"pm_score": 0,
"selected": false,
"text": "<p>The problem with your code is that you passed zero parameters, but the <a href=\"https://codex.wordpress.org/Post_Status_Transitions#.7Bold_status.7D_to_.7Bnew_status.7D_Hook\" rel=\"nofollow noreferrer\">documentation</a> clearly specifies that:</p>\n\n<blockquote>\n <p>It is necessary to specify the number of arguments <code>do_action()</code> should pass to the callback function.</p>\n</blockquote>\n\n<p>Also another nice thing to know: this hook does not run if you click on <code>new post</code>, type in the title and immediately hit the <code>publish</code> button. It only runs if you wait for WordPress to generate the URL for the post! It is because of a <code>DOING_AUTOSAVE</code> condition in the core function.</p>\n\n<p>So here is the corrected code for you:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'new_to_publish', 'conditional_email', 10, 1);\n\n/**\n * Send emails based on categories when a post is published\n *\n * @param \\WP_Post $post\n */\nfunction conditional_email( $post ) {\n wp_mail( '[email protected]', 'test', 'test' );\n}\n</code></pre>\n"
}
] |
2016/12/14
|
[
"https://wordpress.stackexchange.com/questions/249237",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101761/"
] |
I'm using [feed to post RSS Aggregator] and get posts from 44 sites. main page loading is too slow. I checked GTmetrix and it seems good but I don't know how can I improve my website loading. <http://akhbartop.ir/>
|
You need to add parameters `$old_status` and `$new_status` to the function.
```
function conditional_email( $old_status, $new_status) {
wp_mail('[email protected]','test','test');
}
```
You will see that in the example [here](https://codex.wordpress.org/Post_Status_Transitions)
Hope it works after !
|
249,248 |
<p>So I've got to edit my 404 page. Since my client's website has 5 languages, I'd like to let him edit and translate the 404 page by himself, with normal WordPress editor. Also, we're currently using Polylang as the localization plugin.</p>
<p>Is there a way to have the theme's <code>404.php</code> as a regular page?</p>
<p>I've tried to create a page and then assign it to the 404 template via template name, but it doesn't work, because it seems that <code>$post</code> is not available inside the template, so I cannot write contents.</p>
|
[
{
"answer_id": 249260,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": 1,
"selected": false,
"text": "<p>Found a way.</p>\n\n<ul>\n<li><p>Create a regular page for 404 content, say 'Page not found';</p></li>\n<li><p>In your 404.php file, get that page data and then write down your content or whatever... </p></li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>$page = get_page_by_title(\"Page not found\"); \nif($page) echo apply_filters('the_content',$page->post_content);\n</code></pre>\n\n<p>Obviously, you can do a lot more... </p>\n"
},
{
"answer_id": 249261,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>First of all, you should avoid <code>Error 404</code> on your sites absolutely and unconditionally.</p>\n\n<p>Second, you can use a text widget somewhere on the <code>404.php</code> page. Put the following code into the <code>functions.php</code> to register a sidebar to put the widget in:</p>\n\n<pre><code><?php\n\nfunction error_404_widget_init() {\n\n register_sidebar( array(\n 'name' => 'Error 404 widget',\n 'id' => 'error_404',\n 'before_widget' => '<div>',\n 'after_widget' => '</div>',\n 'before_title' => '<h2 class=\"rounded\">',\n 'after_title' => '</h2>',\n ) );\n\n}\nadd_action( 'widgets_init', 'error_404_widget_init' );\n</code></pre>\n\n<p>And add the following into <code>404.php</code> template file, in the place you like:</p>\n\n<pre><code><?php\ndynamic_sidebar( 'error_404' );\n</code></pre>\n\n<p>After that you'll be able to add the widget to the sidebar and specify a text for each language using Polylang's default functionality.</p>\n\n<ul>\n<li>See <a href=\"https://codex.wordpress.org/Widgetizing_Themes\" rel=\"nofollow noreferrer\">Widgetizing Themes</a></li>\n</ul>\n"
}
] |
2016/12/14
|
[
"https://wordpress.stackexchange.com/questions/249248",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
] |
So I've got to edit my 404 page. Since my client's website has 5 languages, I'd like to let him edit and translate the 404 page by himself, with normal WordPress editor. Also, we're currently using Polylang as the localization plugin.
Is there a way to have the theme's `404.php` as a regular page?
I've tried to create a page and then assign it to the 404 template via template name, but it doesn't work, because it seems that `$post` is not available inside the template, so I cannot write contents.
|
Found a way.
* Create a regular page for 404 content, say 'Page not found';
* In your 404.php file, get that page data and then write down your content or whatever...
For example:
```
$page = get_page_by_title("Page not found");
if($page) echo apply_filters('the_content',$page->post_content);
```
Obviously, you can do a lot more...
|
249,309 |
<p>I logged into my wp-dashboard after a hack to find that there is a 'ghost' administrator of my site... the only problem is, I can't just list the user table and delete it. I don't know why, but here's all I get when I click on the Admin tab, or the subscribers tab for that matter:</p>
<p><a href="https://www.dropbox.com/s/uf0uxw40le82yaa/Screenshot%202016-12-14%2021.59.54.png?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/uf0uxw40le82yaa/Screenshot%202016-12-14%2021.59.54.png?dl=0</a></p>
<p>It only lists me!</p>
<p>So, I know that the meta value for an admin is in the wp-usermeta and then wp-capabilities table... and is: meta_value='a:1:{s:13:"administrator";b:1;}</p>
<p>However, I'm really new to phpmyadmin, and I have no idea how to search for this. It doesn't even look like I have this table either:</p>
<p><a href="https://www.dropbox.com/s/cpkbtpihlymds9b/Screenshot%202016-12-14%2022.03.38.png?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/cpkbtpihlymds9b/Screenshot%202016-12-14%2022.03.38.png?dl=0</a></p>
<p>No idea where to go from here :-(</p>
<p>Your help would be much appreciated. Thanks for your time!</p>
|
[
{
"answer_id": 249325,
"author": "Self Designs",
"author_id": 75780,
"author_profile": "https://wordpress.stackexchange.com/users/75780",
"pm_score": 1,
"selected": false,
"text": "<p>Navigate to the wp_users table on your php myadmin and see if you are the only one on the table. If so consider changing your wordpress password and database username or password. They could be using your account if theres no other users in the table</p>\n\n<p><strong>Edit</strong>:</p>\n\n<p>Only just noticed you have many subscribers to the website. To check who is admin on wordpress under the wordpress meta tag look for anyone else with this input. Then delete the user. This will be the other admin</p>\n\n<p>a:1:{s:13:\"administrator\";b:1;}</p>\n"
},
{
"answer_id": 249332,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<p>We can generate the SQL with:</p>\n\n<pre><code>$query = new WP_User_Query( \n [ \n 'role' => 'Administrator',\n 'count_total' => false,\n ]\n);\n\necho $query->request;\n</code></pre>\n\n<p>that outputs:</p>\n\n<pre><code>SELECT wp_users.* \nFROM wp_users \nINNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) \nWHERE 1=1 \n AND ( ( ( wp_usermeta.meta_key = 'wp_capabilities' \n AND wp_usermeta.meta_value LIKE '%\\\"Administrator\\\"%' ) ) ) \nORDER BY user_login ASC\n</code></pre>\n\n<p>You might have a different table prefix, than showed here.</p>\n\n<p>Note that deleting the hidden administrator user, will most likely not fix the problem, as there might still be other backdoor(s). Recovering hacked sites is in general off topic here, but you could try to contact your hosting provider or security experts, regarding available backups, security reviews, etc.</p>\n"
},
{
"answer_id": 300212,
"author": "Greg Much",
"author_id": 131594,
"author_profile": "https://wordpress.stackexchange.com/users/131594",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT u.ID, u.user_login, u.user_nicename, u.user_email\nFROM wp_users u\nINNER JOIN wp_usermeta m ON m.user_id = u.ID\nWHERE m.meta_key = 'wp_capabilities'\nAND m.meta_value LIKE '%administrator%'\nORDER BY u.user_registered\n</code></pre>\n\n<p>Look at the database prefixes.</p>\n"
},
{
"answer_id": 340703,
"author": "Joshua",
"author_id": 170135,
"author_profile": "https://wordpress.stackexchange.com/users/170135",
"pm_score": 0,
"selected": false,
"text": "<pre><code>FROM wp_users INNER JOIN wp_usermeta \nON wp_users.ID = wp_usermeta.user_id \nWHERE wp_usermeta.meta_key = 'wp_capabilities' \nAND wp_usermeta.meta_value LIKE '%Administrator%' \nORDER BY wp_users.user_nicename```\n</code></pre>\n"
}
] |
2016/12/15
|
[
"https://wordpress.stackexchange.com/questions/249309",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108987/"
] |
I logged into my wp-dashboard after a hack to find that there is a 'ghost' administrator of my site... the only problem is, I can't just list the user table and delete it. I don't know why, but here's all I get when I click on the Admin tab, or the subscribers tab for that matter:
<https://www.dropbox.com/s/uf0uxw40le82yaa/Screenshot%202016-12-14%2021.59.54.png?dl=0>
It only lists me!
So, I know that the meta value for an admin is in the wp-usermeta and then wp-capabilities table... and is: meta\_value='a:1:{s:13:"administrator";b:1;}
However, I'm really new to phpmyadmin, and I have no idea how to search for this. It doesn't even look like I have this table either:
<https://www.dropbox.com/s/cpkbtpihlymds9b/Screenshot%202016-12-14%2022.03.38.png?dl=0>
No idea where to go from here :-(
Your help would be much appreciated. Thanks for your time!
|
We can generate the SQL with:
```
$query = new WP_User_Query(
[
'role' => 'Administrator',
'count_total' => false,
]
);
echo $query->request;
```
that outputs:
```
SELECT wp_users.*
FROM wp_users
INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id )
WHERE 1=1
AND ( ( ( wp_usermeta.meta_key = 'wp_capabilities'
AND wp_usermeta.meta_value LIKE '%\"Administrator\"%' ) ) )
ORDER BY user_login ASC
```
You might have a different table prefix, than showed here.
Note that deleting the hidden administrator user, will most likely not fix the problem, as there might still be other backdoor(s). Recovering hacked sites is in general off topic here, but you could try to contact your hosting provider or security experts, regarding available backups, security reviews, etc.
|
249,330 |
<p>I want to run a WordPress code Snippet that can show total posts by author.
something like this:</p>
<p>author1: 37 posts
author2: 12 posts
author3: 43 posts</p>
<p>is possible this?.
Thank you</p>
|
[
{
"answer_id": 249333,
"author": "Ranuka",
"author_id": 106350,
"author_profile": "https://wordpress.stackexchange.com/users/106350",
"pm_score": 1,
"selected": false,
"text": "<p>First of all you need to get all users calling <code>get_users()</code> function. Then you can use <code>count_user_posts()</code> to display post count for a user.</p>\n\n<p>Try below code.</p>\n\n<pre><code> <?php\n $blogusers = get_users();\n // Array of WP_User objects.\n foreach ( $blogusers as $user ) {\n echo 'Number of posts published by '.esc_html($user->display_name).': ' . count_user_posts( esc_html($user->id) ).'</br>';\n } \n ?>\n</code></pre>\n\n<p><strong>Update : You can easily use <code>wp_list_authors()</code> function also.</strong></p>\n\n<pre><code><?php wp_list_authors('show_fullname=1&optioncount=1&orderby=post_count&order=DESC'); ?>\n</code></pre>\n"
},
{
"answer_id": 249334,
"author": "Subhasis Bera",
"author_id": 109000,
"author_profile": "https://wordpress.stackexchange.com/users/109000",
"pm_score": 0,
"selected": false,
"text": "<p>Yaa I can help you just rectify the previous code a little bit... need some small change.</p>\n\n<pre><code>count_user_posts( esc_html( $user->ID ) )\n</code></pre>\n\n<p>Please try this. You'll get the required results. Thanks.</p>\n"
},
{
"answer_id": 249350,
"author": "Subhasis Bera",
"author_id": 109000,
"author_profile": "https://wordpress.stackexchange.com/users/109000",
"pm_score": 0,
"selected": false,
"text": "<p>I think the problem is in your case get_users() is not working that means this function is not being called at all & not returning the existing data....whereas it's working perfect for us.</p>\n\n<p>get_users() is one of the WordPress default functions & I also have confusions that where are you just trying to execute this code ?? </p>\n\n<p>You need to execute this code on respective script into wp-content/themes/ folder . Plz let me know your feedback.</p>\n"
}
] |
2016/12/15
|
[
"https://wordpress.stackexchange.com/questions/249330",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108998/"
] |
I want to run a WordPress code Snippet that can show total posts by author.
something like this:
author1: 37 posts
author2: 12 posts
author3: 43 posts
is possible this?.
Thank you
|
First of all you need to get all users calling `get_users()` function. Then you can use `count_user_posts()` to display post count for a user.
Try below code.
```
<?php
$blogusers = get_users();
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
echo 'Number of posts published by '.esc_html($user->display_name).': ' . count_user_posts( esc_html($user->id) ).'</br>';
}
?>
```
**Update : You can easily use `wp_list_authors()` function also.**
```
<?php wp_list_authors('show_fullname=1&optioncount=1&orderby=post_count&order=DESC'); ?>
```
|
249,429 |
<p>I created a plugin to override a theme's function. As I learn that function in plugin loads first but I got an error </p>
<blockquote>
<p>Fatal error: Cannot redeclare wooc_extra_register_fields() (previously
declared in ****/themes/****/functions.php:247) in
***/plugins/custom-plugin/custom-plugin.php on line 89</p>
</blockquote>
<p>Not sure what I am doing wrong.
Also put theme's functions need to be override in if !function exist.
So what is the right way to override a theme function wrap in !function exist using a plugin??</p>
|
[
{
"answer_id": 249333,
"author": "Ranuka",
"author_id": 106350,
"author_profile": "https://wordpress.stackexchange.com/users/106350",
"pm_score": 1,
"selected": false,
"text": "<p>First of all you need to get all users calling <code>get_users()</code> function. Then you can use <code>count_user_posts()</code> to display post count for a user.</p>\n\n<p>Try below code.</p>\n\n<pre><code> <?php\n $blogusers = get_users();\n // Array of WP_User objects.\n foreach ( $blogusers as $user ) {\n echo 'Number of posts published by '.esc_html($user->display_name).': ' . count_user_posts( esc_html($user->id) ).'</br>';\n } \n ?>\n</code></pre>\n\n<p><strong>Update : You can easily use <code>wp_list_authors()</code> function also.</strong></p>\n\n<pre><code><?php wp_list_authors('show_fullname=1&optioncount=1&orderby=post_count&order=DESC'); ?>\n</code></pre>\n"
},
{
"answer_id": 249334,
"author": "Subhasis Bera",
"author_id": 109000,
"author_profile": "https://wordpress.stackexchange.com/users/109000",
"pm_score": 0,
"selected": false,
"text": "<p>Yaa I can help you just rectify the previous code a little bit... need some small change.</p>\n\n<pre><code>count_user_posts( esc_html( $user->ID ) )\n</code></pre>\n\n<p>Please try this. You'll get the required results. Thanks.</p>\n"
},
{
"answer_id": 249350,
"author": "Subhasis Bera",
"author_id": 109000,
"author_profile": "https://wordpress.stackexchange.com/users/109000",
"pm_score": 0,
"selected": false,
"text": "<p>I think the problem is in your case get_users() is not working that means this function is not being called at all & not returning the existing data....whereas it's working perfect for us.</p>\n\n<p>get_users() is one of the WordPress default functions & I also have confusions that where are you just trying to execute this code ?? </p>\n\n<p>You need to execute this code on respective script into wp-content/themes/ folder . Plz let me know your feedback.</p>\n"
}
] |
2016/12/16
|
[
"https://wordpress.stackexchange.com/questions/249429",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52602/"
] |
I created a plugin to override a theme's function. As I learn that function in plugin loads first but I got an error
>
> Fatal error: Cannot redeclare wooc\_extra\_register\_fields() (previously
> declared in \*\*\*\*/themes/\*\*\*\*/functions.php:247) in
> \*\*\*/plugins/custom-plugin/custom-plugin.php on line 89
>
>
>
Not sure what I am doing wrong.
Also put theme's functions need to be override in if !function exist.
So what is the right way to override a theme function wrap in !function exist using a plugin??
|
First of all you need to get all users calling `get_users()` function. Then you can use `count_user_posts()` to display post count for a user.
Try below code.
```
<?php
$blogusers = get_users();
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
echo 'Number of posts published by '.esc_html($user->display_name).': ' . count_user_posts( esc_html($user->id) ).'</br>';
}
?>
```
**Update : You can easily use `wp_list_authors()` function also.**
```
<?php wp_list_authors('show_fullname=1&optioncount=1&orderby=post_count&order=DESC'); ?>
```
|
249,437 |
<p>I have created a new role .Now I want to remove <strong>post</strong> ,<strong>media</strong>, <strong>setting</strong> capability for that role.
How can I achieve this?</p>
|
[
{
"answer_id": 249440,
"author": "ehabdevel",
"author_id": 109068,
"author_profile": "https://wordpress.stackexchange.com/users/109068",
"pm_score": 1,
"selected": false,
"text": "<p>Remove a top level admin menu:</p>\n\n<pre><code> function custom_menu_page_removing() {\n remove_menu_page( $menu_slug );\n}\nadd_action( 'admin_menu', 'custom_menu_page_removing' );\n</code></pre>\n\n<p>To remove only certain menu items include only those you want to hide within the function. \nTo remove menus for only certain users you may want to utilize current_user_can().</p>\n\n<p>You can take a look at <a href=\"https://codex.wordpress.org/Function_Reference/remove_menu_page\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/remove_menu_page</a></p>\n"
},
{
"answer_id": 249444,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Would you be so kind to try this:</p>\n\n<pre><code>$data = get_userdata( 1 ); // or any other ID where your new role works\nif ( !empty( $data) ) {\n $user_caps = $data->allcaps;\n echo '<pre>' . print_r( $user_caps, true ) . '</pre>';\n}\n</code></pre>\n\n<p>You will get the idea of capabilities on your end.</p>\n\n<pre><code>Array\n(\n [switch_themes] => 1\n [edit_themes] => 1\n [activate_plugins] => 1\n [edit_plugins] => 1\n [edit_users] => 1\n [edit_files] => 1\n [manage_options] => 1\n [moderate_comments] => 1\n [manage_categories] => 1\n [manage_links] => 1\n [upload_files] => 1\n [import] => 1\n [unfiltered_html] => 1\n [edit_posts] => 1\n [edit_others_posts] => 1\n [edit_published_posts] => 1\n [publish_posts] => 1\n [edit_pages] => 1\n [read] => 1\n [level_10] => 1\n [level_9] => 1\n [level_8] => 1\n [level_7] => 1\n [level_6] => 1\n [level_5] => 1\n [level_4] => 1\n [level_3] => 1\n [level_2] => 1\n [level_1] => 1\n [level_0] => 1\n [edit_others_pages] => 1\n [edit_published_pages] => 1\n [publish_pages] => 1\n [delete_pages] => 1\n [delete_others_pages] => 1\n [delete_published_pages] => 1\n [delete_posts] => 1\n [delete_others_posts] => 1\n [delete_published_posts] => 1\n [delete_private_posts] => 1\n [edit_private_posts] => 1\n [read_private_posts] => 1\n [delete_private_pages] => 1\n [edit_private_pages] => 1\n [read_private_pages] => 1\n [delete_users] => 1\n [create_users] => 1\n [unfiltered_upload] => 1\n [edit_dashboard] => 1\n [update_plugins] => 1\n [delete_plugins] => 1\n [install_plugins] => 1\n [update_themes] => 1\n [install_themes] => 1\n [update_core] => 1\n [list_users] => 1\n [remove_users] => 1\n [promote_users] => 1\n [edit_theme_options] => 1\n [delete_themes] => 1\n [export] => 1\n [view_query_monitor] => 1\n [administrator] => 1\n)\n</code></pre>\n\n<p>Then remove them simple with this code:</p>\n\n<pre><code>// Remove a capability from a specific user.\n$user_id = // The ID of the user to remove the capability from.\n$user = new WP_User( $user_id );\n$user->remove_cap( 'read_private_posts' );\n</code></pre>\n\n<p>from <a href=\"https://codex.wordpress.org/Function_Reference/remove_cap\" rel=\"nofollow noreferrer\">ref</a>.</p>\n"
}
] |
2016/12/16
|
[
"https://wordpress.stackexchange.com/questions/249437",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109067/"
] |
I have created a new role .Now I want to remove **post** ,**media**, **setting** capability for that role.
How can I achieve this?
|
Remove a top level admin menu:
```
function custom_menu_page_removing() {
remove_menu_page( $menu_slug );
}
add_action( 'admin_menu', 'custom_menu_page_removing' );
```
To remove only certain menu items include only those you want to hide within the function.
To remove menus for only certain users you may want to utilize current\_user\_can().
You can take a look at <https://codex.wordpress.org/Function_Reference/remove_menu_page>
|
249,438 |
<p>I have written a plugin for my own site where I have an issue like "after user login to the site if he logout then again if he clicks on browser back button then the previous page showing again instead of login page". for this issue I fixed it by using below js code:</p>
<pre><code>history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
</code></pre>
<p>The browser back button issue fixed but after adding the above js code I got new issue i.e. browser back button totally getting disabled, what if user wants to use browser back button to navigate through the site web pages? </p>
<p><strong>IS there any hook that I can write in theme functions.php file?</strong> so that I can fix this issue if user clicks on browser back button after logout? can anyone please tell me how to fix it?</p>
<p>I tried the one below but din't work either:</p>
<pre><code><script>
window.onhashchange = function() {
<?php if( ! is_user_logged_in()) { $this->tewa_login(); } ?>
}
<script>
</code></pre>
<p>what's wrong plz can anyone tell me! </p>
|
[
{
"answer_id": 249443,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>When a user <a href=\"https://codex.wordpress.org/Function_Reference/wp_logout\" rel=\"nofollow noreferrer\">logs out</a> the current user session is destroyed and no new pages can be loaded for which a user must be logged in. However, when you hit the 'back' button on your browser, it typically retrieves the page from the local cache. There is no contact with the server to see if the current session is still valid.</p>\n\n<p>So, what you need to do is detect whether the backspace button has been hit and in that case check the validity of the session. This means there must be a piece of javacript included in the page, because this action needs to take place at the user side. I'm not a security expert, but the common way to detect the backspace goes like this:</p>\n\n<pre><code>window.onhashchange = function() {\n .. your action ..\n }\n</code></pre>\n\n<p>There are <a href=\"https://stackoverflow.com/questions/25806608/how-to-detect-browser-back-button-event-cross-browser\">some snags</a> to this method. Now, your action must be to call back to the server. That question <a href=\"https://wordpress.stackexchange.com/questions/69814/check-if-user-is-logged-in-using-jquery\">has been answered before</a> here on WPSE.</p>\n"
},
{
"answer_id": 249447,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>Just some appendix to @cjbj answer. It may help you, this is why I am writing this.</p>\n\n<p>WordPress \"session\" is actually a cookie. It starts with <code>wordpress_logged_in</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/UDwl2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UDwl2.png\" alt=\"enter image description here\"></a></p>\n\n<p>Once you log out:</p>\n\n<p><a href=\"https://i.stack.imgur.com/AwTtt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AwTtt.png\" alt=\"enter image description here\"></a></p>\n\n<p>Once you refresh still there will be no cookie:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bRdtC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bRdtC.png\" alt=\"enter image description here\"></a></p>\n\n<p>So what you need to understand:</p>\n\n<blockquote>\n <p>if he clicks on browser back button then the previous page showing again instead of login page\".</p>\n</blockquote>\n\n<p>This is not an issue, this is normal.</p>\n\n<p>If you plan to alter the default, try using the JavaScript page refresh or so.</p>\n"
}
] |
2016/12/16
|
[
"https://wordpress.stackexchange.com/questions/249438",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106542/"
] |
I have written a plugin for my own site where I have an issue like "after user login to the site if he logout then again if he clicks on browser back button then the previous page showing again instead of login page". for this issue I fixed it by using below js code:
```
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
```
The browser back button issue fixed but after adding the above js code I got new issue i.e. browser back button totally getting disabled, what if user wants to use browser back button to navigate through the site web pages?
**IS there any hook that I can write in theme functions.php file?** so that I can fix this issue if user clicks on browser back button after logout? can anyone please tell me how to fix it?
I tried the one below but din't work either:
```
<script>
window.onhashchange = function() {
<?php if( ! is_user_logged_in()) { $this->tewa_login(); } ?>
}
<script>
```
what's wrong plz can anyone tell me!
|
When a user [logs out](https://codex.wordpress.org/Function_Reference/wp_logout) the current user session is destroyed and no new pages can be loaded for which a user must be logged in. However, when you hit the 'back' button on your browser, it typically retrieves the page from the local cache. There is no contact with the server to see if the current session is still valid.
So, what you need to do is detect whether the backspace button has been hit and in that case check the validity of the session. This means there must be a piece of javacript included in the page, because this action needs to take place at the user side. I'm not a security expert, but the common way to detect the backspace goes like this:
```
window.onhashchange = function() {
.. your action ..
}
```
There are [some snags](https://stackoverflow.com/questions/25806608/how-to-detect-browser-back-button-event-cross-browser) to this method. Now, your action must be to call back to the server. That question [has been answered before](https://wordpress.stackexchange.com/questions/69814/check-if-user-is-logged-in-using-jquery) here on WPSE.
|
249,456 |
<p>I'm interested in using an old version of a plugin for a core feature on the site (it's not ideal but a compromise after months of effort) because the new version has incompatibilities. However I'm worried that someone - including myself - will mindlessly update the plugin in the future.</p>
<p>Is there any way to prevent a WordPress plugin from searching for updates?</p>
|
[
{
"answer_id": 249482,
"author": "marikamitsos",
"author_id": 17797,
"author_profile": "https://wordpress.stackexchange.com/users/17797",
"pm_score": 2,
"selected": false,
"text": "<p>It is quite simple. All you have to do is add some code in a Custom Functions plugin.</p>\n\n<p>Lets say you want to block the \"Hello Dolly\" plugin (comes prepacked with WordPress) from updating. In your \"My Functions Plugin\", <code>mycustomfunctions.php</code> (you can use any name really) you place the following:</p>\n\n<pre><code>/* Disable a plugin from updating */\nfunction disable_plugin_updating( $value ) {\n unset( $value->response['hello.php'] );\n return $value;\n}\nadd_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );\n</code></pre>\n\n<p>That is all.<br>\nNow in case you want to prevent more than one plugins from updating, you just add additional lines to the above code like this: </p>\n\n<pre><code>/* Disable some plugins from updating */\nfunction disable_plugin_updating( $value ) {\n unset( $value->response['hello.php'] );\n unset( $value->response[ 'akismet/akismet.php' ] );\n return $value;\n}\nadd_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );\n</code></pre>\n\n<p><strong>Things to notice</strong>: </p>\n\n<ul>\n<li><p>It is always best practice to <strong>keep everything updated to the latest version</strong> (for obvious reasons and mainly for vulnerability issues). </p></li>\n<li><p>We use <code>akismet/akismet.php</code> because <code>akismet.php</code> is within the plugin folder <code>akismet</code> </p></li>\n<li><p>In case you are not aware of what a Custom Functions plugin is (or don't have one) you can easily create one. Please have a look at an old -but still very valid- post on: <a href=\"http://justintadlock.com/archives/2011/02/02/creating-a-custom-functions-plugin-for-end-users\" rel=\"nofollow noreferrer\">Creating a custom functions plugin for end users</a>. </p></li>\n<li><p>Also, please have a look at this post about: <a href=\"https://wordpress.stackexchange.com/questions/73031/where-to-put-my-code-plugin-or-functions-php\">Where to put my code: plugin or functions.php</a>. </p></li>\n</ul>\n"
},
{
"answer_id": 249578,
"author": "Faruque Ahamed Mollick",
"author_id": 101391,
"author_profile": "https://wordpress.stackexchange.com/users/101391",
"pm_score": 1,
"selected": false,
"text": "<p>You can easily stop WordPress plugins from searching for updates just with this code:</p>\n\n<pre><code>function filter_plugin_updates( $value ) {\nunset( $value->response['PATH_TO_PLUGIN_MAIN_FILE'] ); //Replace the path with main PHP file of your plugin.\nreturn $value;}\nadd_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );\n</code></pre>\n\n<p>I have written a complete blog post on it. Here is my blog post - <a href=\"https://www.codespeedy.com/prevent-a-wordpress-plugin-from-searching-for-updates/\" rel=\"nofollow noreferrer\">Prevent a WordPress plugin from searching for updates</a>. This blog will show you how and wheere to use this blog. And also give you the suggestion to use it in perfect place.</p>\n\n<p>Source: <a href=\"https://www.codespeedy.com/prevent-a-wordpress-plugin-from-searching-for-updates/\" rel=\"nofollow noreferrer\">https://www.codespeedy.com/prevent-a-wordpress-plugin-from-searching-for-updates/</a></p>\n"
},
{
"answer_id": 363044,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>One-Line version is also good to insert into current plugin's construction:</p>\n\n<pre><code>add_filter('site_transient_update_plugins', function ($value) { if ( isset($value->response[$name=plugin_basename(__FILE__)]) ) { unset($value->response[$name]); } return $value; });\n</code></pre>\n"
}
] |
2016/12/16
|
[
"https://wordpress.stackexchange.com/questions/249456",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96983/"
] |
I'm interested in using an old version of a plugin for a core feature on the site (it's not ideal but a compromise after months of effort) because the new version has incompatibilities. However I'm worried that someone - including myself - will mindlessly update the plugin in the future.
Is there any way to prevent a WordPress plugin from searching for updates?
|
It is quite simple. All you have to do is add some code in a Custom Functions plugin.
Lets say you want to block the "Hello Dolly" plugin (comes prepacked with WordPress) from updating. In your "My Functions Plugin", `mycustomfunctions.php` (you can use any name really) you place the following:
```
/* Disable a plugin from updating */
function disable_plugin_updating( $value ) {
unset( $value->response['hello.php'] );
return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );
```
That is all.
Now in case you want to prevent more than one plugins from updating, you just add additional lines to the above code like this:
```
/* Disable some plugins from updating */
function disable_plugin_updating( $value ) {
unset( $value->response['hello.php'] );
unset( $value->response[ 'akismet/akismet.php' ] );
return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );
```
**Things to notice**:
* It is always best practice to **keep everything updated to the latest version** (for obvious reasons and mainly for vulnerability issues).
* We use `akismet/akismet.php` because `akismet.php` is within the plugin folder `akismet`
* In case you are not aware of what a Custom Functions plugin is (or don't have one) you can easily create one. Please have a look at an old -but still very valid- post on: [Creating a custom functions plugin for end users](http://justintadlock.com/archives/2011/02/02/creating-a-custom-functions-plugin-for-end-users).
* Also, please have a look at this post about: [Where to put my code: plugin or functions.php](https://wordpress.stackexchange.com/questions/73031/where-to-put-my-code-plugin-or-functions-php).
|
249,472 |
<p>I have written a code for inserting wordpress user if I try to add new user I am getting 3 warning errors saying like below: </p>
<p>"Warning: mysql_real_escape_string() expects parameter 1 to be string, object given in /home/intecom/public_html/app/wp-includes/wp-db.php on line 1129
" , </p>
<p>"Warning: Illegal offset type in isset or empty in /home/intecom/public_html/app/wp-includes/cache.php on line 725" </p>
<p>and </p>
<p>"Warning: array_key_exists(): The first argument should be either a string or an integer in /home/intecom/public_html/app/wp-includes/cache.php on line 725". </p>
<p>my code is below:</p>
<pre><code> $first_name = 'my_firstname_value';
$last_name = 'my_lastname_value';
$trainer_email = '[email protected]';
$course_registered = Array
(
[0] => 2410
);
$pro_icon_status = '1';
$this->institute_icon[0] = '1';
$this->institute_name[0] = 'my_institute_name';
$user_data = array(
'user_login' => $first_name,
'user_pass' => '',
'user_email' => $trainer_email,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => 'trainer'
);
$random_password = wp_generate_password(8,false);
$user_id = wp_insert_user( $user_data );
update_user_meta( $user_id, 'course_registered',$course_registered );
update_user_meta( $user_id, 'inistitute_name',$this->institute_name[0] );
update_user_meta( $user_id, 'inistitute_icon',$this->institute_icon[0] );
update_user_meta( $user_id, 'trainer_icon',$pro_icon_status );
wp_set_password($random_password, $user_id);
</code></pre>
<p>My input is only either string (or) array but why it is saying that "Iam passing object" I don't know what is happening. It is driving me nuts. can any one please tell me what was my mistake? Thanks in advance.</p>
<p>Update: The problem is not with 'wp_insert_user' or 'update_user_meta', actual problem is with the data that I was giving i.e. Am giving the same user_login name which is already there in the database, I am getting the WP_Error Object as below:</p>
<pre><code> WP_Error Object
(
[errors] => Array
(
[existing_user_login] => Array
(
[0] => Sorry, that username already exists!
)
)
[error_data] => Array
(
)
)
</code></pre>
<p>Now can u plz tell me how to show that error to user on the front end?</p>
|
[
{
"answer_id": 249482,
"author": "marikamitsos",
"author_id": 17797,
"author_profile": "https://wordpress.stackexchange.com/users/17797",
"pm_score": 2,
"selected": false,
"text": "<p>It is quite simple. All you have to do is add some code in a Custom Functions plugin.</p>\n\n<p>Lets say you want to block the \"Hello Dolly\" plugin (comes prepacked with WordPress) from updating. In your \"My Functions Plugin\", <code>mycustomfunctions.php</code> (you can use any name really) you place the following:</p>\n\n<pre><code>/* Disable a plugin from updating */\nfunction disable_plugin_updating( $value ) {\n unset( $value->response['hello.php'] );\n return $value;\n}\nadd_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );\n</code></pre>\n\n<p>That is all.<br>\nNow in case you want to prevent more than one plugins from updating, you just add additional lines to the above code like this: </p>\n\n<pre><code>/* Disable some plugins from updating */\nfunction disable_plugin_updating( $value ) {\n unset( $value->response['hello.php'] );\n unset( $value->response[ 'akismet/akismet.php' ] );\n return $value;\n}\nadd_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );\n</code></pre>\n\n<p><strong>Things to notice</strong>: </p>\n\n<ul>\n<li><p>It is always best practice to <strong>keep everything updated to the latest version</strong> (for obvious reasons and mainly for vulnerability issues). </p></li>\n<li><p>We use <code>akismet/akismet.php</code> because <code>akismet.php</code> is within the plugin folder <code>akismet</code> </p></li>\n<li><p>In case you are not aware of what a Custom Functions plugin is (or don't have one) you can easily create one. Please have a look at an old -but still very valid- post on: <a href=\"http://justintadlock.com/archives/2011/02/02/creating-a-custom-functions-plugin-for-end-users\" rel=\"nofollow noreferrer\">Creating a custom functions plugin for end users</a>. </p></li>\n<li><p>Also, please have a look at this post about: <a href=\"https://wordpress.stackexchange.com/questions/73031/where-to-put-my-code-plugin-or-functions-php\">Where to put my code: plugin or functions.php</a>. </p></li>\n</ul>\n"
},
{
"answer_id": 249578,
"author": "Faruque Ahamed Mollick",
"author_id": 101391,
"author_profile": "https://wordpress.stackexchange.com/users/101391",
"pm_score": 1,
"selected": false,
"text": "<p>You can easily stop WordPress plugins from searching for updates just with this code:</p>\n\n<pre><code>function filter_plugin_updates( $value ) {\nunset( $value->response['PATH_TO_PLUGIN_MAIN_FILE'] ); //Replace the path with main PHP file of your plugin.\nreturn $value;}\nadd_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );\n</code></pre>\n\n<p>I have written a complete blog post on it. Here is my blog post - <a href=\"https://www.codespeedy.com/prevent-a-wordpress-plugin-from-searching-for-updates/\" rel=\"nofollow noreferrer\">Prevent a WordPress plugin from searching for updates</a>. This blog will show you how and wheere to use this blog. And also give you the suggestion to use it in perfect place.</p>\n\n<p>Source: <a href=\"https://www.codespeedy.com/prevent-a-wordpress-plugin-from-searching-for-updates/\" rel=\"nofollow noreferrer\">https://www.codespeedy.com/prevent-a-wordpress-plugin-from-searching-for-updates/</a></p>\n"
},
{
"answer_id": 363044,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>One-Line version is also good to insert into current plugin's construction:</p>\n\n<pre><code>add_filter('site_transient_update_plugins', function ($value) { if ( isset($value->response[$name=plugin_basename(__FILE__)]) ) { unset($value->response[$name]); } return $value; });\n</code></pre>\n"
}
] |
2016/12/16
|
[
"https://wordpress.stackexchange.com/questions/249472",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106542/"
] |
I have written a code for inserting wordpress user if I try to add new user I am getting 3 warning errors saying like below:
"Warning: mysql\_real\_escape\_string() expects parameter 1 to be string, object given in /home/intecom/public\_html/app/wp-includes/wp-db.php on line 1129
" ,
"Warning: Illegal offset type in isset or empty in /home/intecom/public\_html/app/wp-includes/cache.php on line 725"
and
"Warning: array\_key\_exists(): The first argument should be either a string or an integer in /home/intecom/public\_html/app/wp-includes/cache.php on line 725".
my code is below:
```
$first_name = 'my_firstname_value';
$last_name = 'my_lastname_value';
$trainer_email = '[email protected]';
$course_registered = Array
(
[0] => 2410
);
$pro_icon_status = '1';
$this->institute_icon[0] = '1';
$this->institute_name[0] = 'my_institute_name';
$user_data = array(
'user_login' => $first_name,
'user_pass' => '',
'user_email' => $trainer_email,
'first_name' => $first_name,
'last_name' => $last_name,
'role' => 'trainer'
);
$random_password = wp_generate_password(8,false);
$user_id = wp_insert_user( $user_data );
update_user_meta( $user_id, 'course_registered',$course_registered );
update_user_meta( $user_id, 'inistitute_name',$this->institute_name[0] );
update_user_meta( $user_id, 'inistitute_icon',$this->institute_icon[0] );
update_user_meta( $user_id, 'trainer_icon',$pro_icon_status );
wp_set_password($random_password, $user_id);
```
My input is only either string (or) array but why it is saying that "Iam passing object" I don't know what is happening. It is driving me nuts. can any one please tell me what was my mistake? Thanks in advance.
Update: The problem is not with 'wp\_insert\_user' or 'update\_user\_meta', actual problem is with the data that I was giving i.e. Am giving the same user\_login name which is already there in the database, I am getting the WP\_Error Object as below:
```
WP_Error Object
(
[errors] => Array
(
[existing_user_login] => Array
(
[0] => Sorry, that username already exists!
)
)
[error_data] => Array
(
)
)
```
Now can u plz tell me how to show that error to user on the front end?
|
It is quite simple. All you have to do is add some code in a Custom Functions plugin.
Lets say you want to block the "Hello Dolly" plugin (comes prepacked with WordPress) from updating. In your "My Functions Plugin", `mycustomfunctions.php` (you can use any name really) you place the following:
```
/* Disable a plugin from updating */
function disable_plugin_updating( $value ) {
unset( $value->response['hello.php'] );
return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );
```
That is all.
Now in case you want to prevent more than one plugins from updating, you just add additional lines to the above code like this:
```
/* Disable some plugins from updating */
function disable_plugin_updating( $value ) {
unset( $value->response['hello.php'] );
unset( $value->response[ 'akismet/akismet.php' ] );
return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updating' );
```
**Things to notice**:
* It is always best practice to **keep everything updated to the latest version** (for obvious reasons and mainly for vulnerability issues).
* We use `akismet/akismet.php` because `akismet.php` is within the plugin folder `akismet`
* In case you are not aware of what a Custom Functions plugin is (or don't have one) you can easily create one. Please have a look at an old -but still very valid- post on: [Creating a custom functions plugin for end users](http://justintadlock.com/archives/2011/02/02/creating-a-custom-functions-plugin-for-end-users).
* Also, please have a look at this post about: [Where to put my code: plugin or functions.php](https://wordpress.stackexchange.com/questions/73031/where-to-put-my-code-plugin-or-functions-php).
|
249,483 |
<p>I have seen many articles mentioning that a <code>/%postname%/</code> permalink is the best for SEO. But what about a <code>/%post_id%/%postname%</code> structure, such as <code>myblog.com/123/the-slug-of-my-blog</code> ?</p>
<ul>
<li>It doesn't seem to affect search engine rankings (Stack Exchange and many others use this structure)</li>
<li>You make each permalink unique, even with the same slug (preventing the dreaded appending of "-2" in the slug)</li>
<li>You can even use <code>myblog.com/123</code> as a short-url, or an easy to say url in a podcast, etc (maybe you need a bit of code customization to achieve this)</li>
</ul>
<p>Is there any known performance issue about this permalink structure?</p>
|
[
{
"answer_id": 249500,
"author": "Game Unity",
"author_id": 83769,
"author_profile": "https://wordpress.stackexchange.com/users/83769",
"pm_score": 0,
"selected": false,
"text": "<p>There shouldn't be any diffrents. I recommend you to use the ID version and you coold even make it prettier like <code>/%postname%-id=%post_id%</code>.</p>\n"
},
{
"answer_id": 346572,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": false,
"text": "<p>Note: we're talking here about the difference between permalinks <code>/%ID%/%name%/</code> and <code>%/name/%</code>. It would be a whole different story if we were to compare <code>/%ID%/%name%/</code> and <code>%/ID/%</code>. </p>\n\n<p>Now, there are two use cases that affect performance:</p>\n\n<p><strong>One. You have a permalink and WP needs to resolve it in order to serve the page requested.</strong></p>\n\n<p>This means setting up the <a href=\"https://developer.wordpress.org/reference/classes/wp/\" rel=\"noreferrer\">WP class</a>. The main function is at the bottom of the code. After init this involves calling <a href=\"https://developer.wordpress.org/reference/classes/wp/parse_request/\" rel=\"noreferrer\"><code>parse_request</code></a>. This checks whether rewrite rules exist for this particular page and checks query variables for validity. In this case we'd like to know whether processing <code>example.com/123/slug</code> takes more time than <code>example.com/slug</code>. For that to matter you would have to assume that the PHP string function that needs to handle a few bytes more has a significant impact on performance.</p>\n\n<p>Once the requested url has been chopped into workable chunks, the action moves to <a href=\"https://developer.wordpress.org/reference/classes/wp_query/parse_query/\" rel=\"noreferrer\"><code>parse_query</code></a>, which in this case will be passed a query object either containing <code>name</code> or both <code>name</code> and <code>ID</code> (confusingly in the query object the ID is called <code>p</code>). A lot of handling is done, but nothing extra for including the ID in the query.</p>\n\n<p>Next follow two hooks in (<code>pre_get_posts</code> and <code>posts_selection</code>) that are plugin territory, so impact on performance is unknown.</p>\n\n<p>Now comes the main issue: will it take more time to query the database with one variable or with two? Both <code>ID</code> and <code>name</code> are stored in the <code>wp_posts</code> table in the database. So, there is no difference in the size of the table that will be queried. Also, both are unique, because when a post is stored this is checked (OP's assumption that including ID in the url will get rid of the <code>-2</code> in posts is wrong, unless you hack the saving procedure). As a result, it doesn't really matter whether you have to query all database rows for the unique <code>ID</code> or the unique <code>name</code>. The only difference in performance when providing both is that after the row with the <code>ID</code> has been found it will check if the <code>name</code> matches. That really is negligible.</p>\n\n<p><strong>Two. You need to generate a permalink on a page.</strong></p>\n\n<p>This is done by the <a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"noreferrer\"><code>get_permalink</code></a> function. For standard post types the procedure only adds some lengthy calculations if you are using <code>%category%</code>. For <code>ID</code> and <code>name</code> it is just a matter of search and replace in this line of code:</p>\n\n<pre><code>$permalink = home_url( str_replace( $rewritecode, $rewritereplace, $permalink ) );\n</code></pre>\n\n<p>The efficiency of <a href=\"https://www.php.net/manual/en/function.str-replace.php\" rel=\"noreferrer\"><code>str_replace</code></a> depends on the size of the parameters that are passed to it, but since all possible rewriting parameters are passed, not just the one or two that are actually used, this does not affect performance.</p>\n\n<p>For custom post types <code>get_permalink</code> refers to <a href=\"https://developer.wordpress.org/reference/functions/get_post_permalink/\" rel=\"noreferrer\"><code>get_post_permalink</code></a>, which involves more calculations anyway, but essentially winds down to the same search and replace.</p>\n"
},
{
"answer_id": 346747,
"author": "Pratikb.Simform",
"author_id": 173473,
"author_profile": "https://wordpress.stackexchange.com/users/173473",
"pm_score": 0,
"selected": false,
"text": "<p>There is no peformance issue with the above permalink and I will say both are good . However /%postname%/ is used widely as it will help you generate better search results and it is also SEO friendly URL.</p>\n\n<p>Getting better rank in SEO is the purpose of any website. Hence the /%postname%/ is most used and preffered permalink structure for all wordpress websites .</p>\n\n<p>/%post_id%/%postname% is also a good option to use but in most of cases people try to get only post name after site on URL to get better results in SEO</p>\n"
},
{
"answer_id": 346921,
"author": "bikegremlin",
"author_id": 153697,
"author_profile": "https://wordpress.stackexchange.com/users/153697",
"pm_score": 2,
"selected": false,
"text": "<p>Having tested on a super-slow shared hosting environment, the post_id/postname option was faster.</p>\n\n<p>I suppose searching for the ID is somehow better indexed - not sure how it works \"under the hood\".</p>\n\n<p>Didn't notice any \"seo\" penalties from having a number added before the post name - suppose there are some, but not that severe, with the content still carrying greater \"weight\".</p>\n\n<p>My tests and the conclusions described at great length:\n<a href=\"https://io.bikegremlin.com/6768/permalink-change/\" rel=\"nofollow noreferrer\">https://io.bikegremlin.com/6768/permalink-change/</a></p>\n"
}
] |
2016/12/16
|
[
"https://wordpress.stackexchange.com/questions/249483",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101799/"
] |
I have seen many articles mentioning that a `/%postname%/` permalink is the best for SEO. But what about a `/%post_id%/%postname%` structure, such as `myblog.com/123/the-slug-of-my-blog` ?
* It doesn't seem to affect search engine rankings (Stack Exchange and many others use this structure)
* You make each permalink unique, even with the same slug (preventing the dreaded appending of "-2" in the slug)
* You can even use `myblog.com/123` as a short-url, or an easy to say url in a podcast, etc (maybe you need a bit of code customization to achieve this)
Is there any known performance issue about this permalink structure?
|
Note: we're talking here about the difference between permalinks `/%ID%/%name%/` and `%/name/%`. It would be a whole different story if we were to compare `/%ID%/%name%/` and `%/ID/%`.
Now, there are two use cases that affect performance:
**One. You have a permalink and WP needs to resolve it in order to serve the page requested.**
This means setting up the [WP class](https://developer.wordpress.org/reference/classes/wp/). The main function is at the bottom of the code. After init this involves calling [`parse_request`](https://developer.wordpress.org/reference/classes/wp/parse_request/). This checks whether rewrite rules exist for this particular page and checks query variables for validity. In this case we'd like to know whether processing `example.com/123/slug` takes more time than `example.com/slug`. For that to matter you would have to assume that the PHP string function that needs to handle a few bytes more has a significant impact on performance.
Once the requested url has been chopped into workable chunks, the action moves to [`parse_query`](https://developer.wordpress.org/reference/classes/wp_query/parse_query/), which in this case will be passed a query object either containing `name` or both `name` and `ID` (confusingly in the query object the ID is called `p`). A lot of handling is done, but nothing extra for including the ID in the query.
Next follow two hooks in (`pre_get_posts` and `posts_selection`) that are plugin territory, so impact on performance is unknown.
Now comes the main issue: will it take more time to query the database with one variable or with two? Both `ID` and `name` are stored in the `wp_posts` table in the database. So, there is no difference in the size of the table that will be queried. Also, both are unique, because when a post is stored this is checked (OP's assumption that including ID in the url will get rid of the `-2` in posts is wrong, unless you hack the saving procedure). As a result, it doesn't really matter whether you have to query all database rows for the unique `ID` or the unique `name`. The only difference in performance when providing both is that after the row with the `ID` has been found it will check if the `name` matches. That really is negligible.
**Two. You need to generate a permalink on a page.**
This is done by the [`get_permalink`](https://developer.wordpress.org/reference/functions/get_permalink/) function. For standard post types the procedure only adds some lengthy calculations if you are using `%category%`. For `ID` and `name` it is just a matter of search and replace in this line of code:
```
$permalink = home_url( str_replace( $rewritecode, $rewritereplace, $permalink ) );
```
The efficiency of [`str_replace`](https://www.php.net/manual/en/function.str-replace.php) depends on the size of the parameters that are passed to it, but since all possible rewriting parameters are passed, not just the one or two that are actually used, this does not affect performance.
For custom post types `get_permalink` refers to [`get_post_permalink`](https://developer.wordpress.org/reference/functions/get_post_permalink/), which involves more calculations anyway, but essentially winds down to the same search and replace.
|
249,485 |
<p>Sorry for the noob question.</p>
<p>Is a text-domain necessary for a child theme? I am building a simple child theme with no text-domain declared. So, when I use strings which are to be translated, should I use the parent theme text-domain (yes parent theme has text-domain loaded and also has .mo/.po files).</p>
<p>For example adding this line in my child theme template </p>
<pre><code><?php __('Some String', 'parent-text-domain');>
</code></pre>
<p>Will be above string be translated?</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 249522,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": true,
"text": "<p><strong>TL;DR:</strong> If you use strings that are in the parent theme, exaclty how they are used in parent theme, you don't need to have a text domain for your child theme.</p>\n<p>But if you use strings that aren't used in parent theme, to make them translatable, you'll need another text domain with related translation (<code>.mo</code>) files.</p>\n<hr />\n<h2>Translation workflow</h2>\n<p>When WordPress encounter a string in a translatation function it:</p>\n<ol>\n<li>Checks if a translation for required text domain has been loaded (via <a href=\"https://developer.wordpress.org/reference/functions/load_plugin_textdomain/\" rel=\"noreferrer\"><code>load_plugin_textdomain</code></a> or <a href=\"https://developer.wordpress.org/reference/functions/load_theme_textdomain/\" rel=\"noreferrer\"><code>load_theme_textdomain</code></a> or <a href=\"https://developer.wordpress.org/reference/functions/load_textdomain/\" rel=\"noreferrer\"><code>load_textdomain</code></a>), if so go to point <em>3.</em></li>\n<li>Checks if translations folder (by default <code>wp-content/languages</code>) contains a matching textdomain file. Matching textdomain file is <code>"{$domain}-{$locale}.mo"</code> where <code>$domain</code> is the text domain of the string to translate and <code>$locale</code> is the current locale for the website. If that file is not found the original string is returned, otherwise it is loaded and WP forwards to next point.</li>\n<li>When the textdomain is loaded, WP looks if the required string is contained in that file, if not the original string is returned, otherwiseWP forwards to next point.</li>\n<li>If the found translated string needs some singular / plural resolution (e.g. when using <a href=\"https://developer.wordpress.org/reference/functions/_n/\" rel=\"noreferrer\"><code>_n()</code></a>) those are done. Otherwise WP forwards to next point.</li>\n<li>Filter hooks are applied on the translated string (see <a href=\"https://developer.wordpress.org/?s=gettext&post_type%5B%5D=wp-parser-hook\" rel=\"noreferrer\">https://developer.wordpress.org/?s=gettext&post_type%5B%5D=wp-parser-hook</a>) and finally the result is returned.</li>\n</ol>\n<h2>So?</h2>\n<p>When you use parent theme text domain in translation function from child theme (assuming parent theme ships and loads the textdomain file, or it has a translation file in translations folder), WordPress will arrive at point <em>3.</em> in the list above, and so if the string is available in the file (because used in parent theme) it will be translated, otherwise not so.</p>\n<p>It means that custom strings in parent theme needs own translation file.</p>\n<p>In theory, it is possible to use parent textdomain in another translation file, because WordPress is capable to load more times the same text domain, "merging" them, but that has issues because only one file may exists in the format <code>"{$domain}-{$locale}.mo"</code> in translation folders (see point <em>2.</em> in the list above).</p>\n<p>So, in conclusion, the only viable way to make a child theme translatable, if it contains strings not used in parent theme, is to use own text domain and own translation file.</p>\n"
},
{
"answer_id": 304630,
"author": "docker",
"author_id": 73427,
"author_profile": "https://wordpress.stackexchange.com/users/73427",
"pm_score": 0,
"selected": false,
"text": "<p>If your child theme conains different strings than the parent theme.</p>\n\n<p>The proper way to use a different textdomain in a child theme is the <code>load_child_theme_textdomain()</code> function now.\nYou can use it the same way as other load_..._textdomain functions.</p>\n\n<p><strong>Beware!</strong> </p>\n\n<blockquote>\n <p>Unlike plugin language files, a name like my_child_theme-de_DE.mo will\n NOT work. Although plugin language files allow you to specify the\n text-domain in the filename, this will NOT work with themes and child\n themes. Language files for themes <strong>should include the language shortcut\n ONLY</strong>.</p>\n</blockquote>\n"
}
] |
2016/12/16
|
[
"https://wordpress.stackexchange.com/questions/249485",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88136/"
] |
Sorry for the noob question.
Is a text-domain necessary for a child theme? I am building a simple child theme with no text-domain declared. So, when I use strings which are to be translated, should I use the parent theme text-domain (yes parent theme has text-domain loaded and also has .mo/.po files).
For example adding this line in my child theme template
```
<?php __('Some String', 'parent-text-domain');>
```
Will be above string be translated?
Thanks in advance
|
**TL;DR:** If you use strings that are in the parent theme, exaclty how they are used in parent theme, you don't need to have a text domain for your child theme.
But if you use strings that aren't used in parent theme, to make them translatable, you'll need another text domain with related translation (`.mo`) files.
---
Translation workflow
--------------------
When WordPress encounter a string in a translatation function it:
1. Checks if a translation for required text domain has been loaded (via [`load_plugin_textdomain`](https://developer.wordpress.org/reference/functions/load_plugin_textdomain/) or [`load_theme_textdomain`](https://developer.wordpress.org/reference/functions/load_theme_textdomain/) or [`load_textdomain`](https://developer.wordpress.org/reference/functions/load_textdomain/)), if so go to point *3.*
2. Checks if translations folder (by default `wp-content/languages`) contains a matching textdomain file. Matching textdomain file is `"{$domain}-{$locale}.mo"` where `$domain` is the text domain of the string to translate and `$locale` is the current locale for the website. If that file is not found the original string is returned, otherwise it is loaded and WP forwards to next point.
3. When the textdomain is loaded, WP looks if the required string is contained in that file, if not the original string is returned, otherwiseWP forwards to next point.
4. If the found translated string needs some singular / plural resolution (e.g. when using [`_n()`](https://developer.wordpress.org/reference/functions/_n/)) those are done. Otherwise WP forwards to next point.
5. Filter hooks are applied on the translated string (see <https://developer.wordpress.org/?s=gettext&post_type%5B%5D=wp-parser-hook>) and finally the result is returned.
So?
---
When you use parent theme text domain in translation function from child theme (assuming parent theme ships and loads the textdomain file, or it has a translation file in translations folder), WordPress will arrive at point *3.* in the list above, and so if the string is available in the file (because used in parent theme) it will be translated, otherwise not so.
It means that custom strings in parent theme needs own translation file.
In theory, it is possible to use parent textdomain in another translation file, because WordPress is capable to load more times the same text domain, "merging" them, but that has issues because only one file may exists in the format `"{$domain}-{$locale}.mo"` in translation folders (see point *2.* in the list above).
So, in conclusion, the only viable way to make a child theme translatable, if it contains strings not used in parent theme, is to use own text domain and own translation file.
|
249,505 |
<p>I need to get all meta keys/custom fields that are assigned to a post type.</p>
<p>I don't want to get the <code>post_meta</code> values for <code>post_meta</code> assigned to a particular post, or to all posts of a post type.</p>
<p>But, I want to get all possible custom fields that are 'assigned' to a post type. </p>
<p>I have looked and I am starting to worry that it's not possible, as maybe <code>post_meta</code> isn't 'registered' but only appears in the database when a post is saved?</p>
<p>I want to get all post meta information for a post type, in the same way I can get all taxonomies' information, assigned to a post type.</p>
<p>I want to be able to do:</p>
<pre><code>get_post_meta_information_for_post_type($post_type);
</code></pre>
<p>and get something like:</p>
<pre><code>array('custom_meta_key_1', 'custom_meta_key_2);
</code></pre>
<p>... regardless of whether or not there is even one single existing post of that post type.</p>
<p>Please tell me it's possible (and how to do it :))?</p>
<p>Thanks</p>
|
[
{
"answer_id": 249508,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 1,
"selected": false,
"text": "<p>query all posts in the post type and then get the meta keys from the posts e.g.</p>\n\n<p><strong>Not tested, may need some amendments</strong></p>\n\n<pre><code>$meta_fields = array();\n$the_query = new WP_Query( 'post_type=posttype' );\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n\n $meta_array = get_post_meta( get_the_ID() );\n foreach( $meta_array as $meta) {\n $meta_fields = $meta[];\n\n } \n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>You can then do whatever you want with the $meta_fields variable</p>\n"
},
{
"answer_id": 348601,
"author": "Rao Abid",
"author_id": 66242,
"author_profile": "https://wordpress.stackexchange.com/users/66242",
"pm_score": 2,
"selected": false,
"text": "<p>Answer by @Gareth Gillman definitely works but its an expensive query if we have hundreds of posts.</p>\n\n<p>The function below is less expensive and using the wp native function <a href=\"https://codex.wordpress.org/Function_Reference/get_post_custom_keys\" rel=\"nofollow noreferrer\">get_post_custom_keys()</a></p>\n\n<pre><code>if ( ! function_exists( 'us_get_meta_keys_for_post_type' ) ) :\n\n function us_get_meta_keys_for_post_type( $post_type, $sample_size = 5 ) {\n\n $meta_keys = array();\n $posts = get_posts( array( 'post_type' => $post_type, 'limit' => $sample_size ) );\n\n\n foreach ( $posts as $post ) {\n $post_meta_keys = get_post_custom_keys( $post->ID );\n $meta_keys = array_merge( $meta_keys, $post_meta_keys );\n }\n\n // Use array_unique to remove duplicate meta_keys that we received from all posts\n // Use array_values to reset the index of the array\n return array_values( array_unique( $meta_keys ) );\n\n }\n\nendif;\n</code></pre>\n\n<p>You may use the $sample_size param to include more posts in the loop.</p>\n\n<p>Hope it helps someone.</p>\n"
},
{
"answer_id": 402559,
"author": "pclalv",
"author_id": 219084,
"author_profile": "https://wordpress.stackexchange.com/users/219084",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that <a href=\"https://developer.wordpress.org/reference/functions/get_registered_meta_keys/\" rel=\"nofollow noreferrer\"><code>get_registered_meta_keys</code></a> will do the trick. Invoke it like this, <code>get_registered_meta_keys( 'post', $post_type )</code>, and it'll return an associative array of all of the meta keys and the data defines them. You can call <code>array_keys( get_registered_meta_keys( 'post', $post_type ) )</code> if you just want the keys.</p>\n<p>I think that this is correct because the source for <a href=\"https://developer.wordpress.org/reference/functions/register_post_meta/\" rel=\"nofollow noreferrer\"><code>register_post_meta</code></a> shows that it simply defines an <code>'object_subtype'</code> key and then delegates to <code>register_meta( 'post', $meta_key, $args )</code>. The <code>$object_type</code> arg and <code>object_subtype</code> key that are used in <code>register_meta</code> seem to line-up exactly with the args that <code>get_registered_meta_keys</code> accepts.</p>\n"
}
] |
2016/12/16
|
[
"https://wordpress.stackexchange.com/questions/249505",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66961/"
] |
I need to get all meta keys/custom fields that are assigned to a post type.
I don't want to get the `post_meta` values for `post_meta` assigned to a particular post, or to all posts of a post type.
But, I want to get all possible custom fields that are 'assigned' to a post type.
I have looked and I am starting to worry that it's not possible, as maybe `post_meta` isn't 'registered' but only appears in the database when a post is saved?
I want to get all post meta information for a post type, in the same way I can get all taxonomies' information, assigned to a post type.
I want to be able to do:
```
get_post_meta_information_for_post_type($post_type);
```
and get something like:
```
array('custom_meta_key_1', 'custom_meta_key_2);
```
... regardless of whether or not there is even one single existing post of that post type.
Please tell me it's possible (and how to do it :))?
Thanks
|
Answer by @Gareth Gillman definitely works but its an expensive query if we have hundreds of posts.
The function below is less expensive and using the wp native function [get\_post\_custom\_keys()](https://codex.wordpress.org/Function_Reference/get_post_custom_keys)
```
if ( ! function_exists( 'us_get_meta_keys_for_post_type' ) ) :
function us_get_meta_keys_for_post_type( $post_type, $sample_size = 5 ) {
$meta_keys = array();
$posts = get_posts( array( 'post_type' => $post_type, 'limit' => $sample_size ) );
foreach ( $posts as $post ) {
$post_meta_keys = get_post_custom_keys( $post->ID );
$meta_keys = array_merge( $meta_keys, $post_meta_keys );
}
// Use array_unique to remove duplicate meta_keys that we received from all posts
// Use array_values to reset the index of the array
return array_values( array_unique( $meta_keys ) );
}
endif;
```
You may use the $sample\_size param to include more posts in the loop.
Hope it helps someone.
|
249,512 |
<p>I've got the opposite problem a lot of people can when switching servers. All the pages work fine, EXCEPT the home page, which is generating a 404. It's just the blog URL by itself (mysite.com/blogfolder/). Wordpress is installed in a folder in the site root, and worked fine at the old host. htaccess is all what it is supposed to be for this kind of installation. What could cause this??</p>
|
[
{
"answer_id": 249508,
"author": "Gareth Gillman",
"author_id": 33936,
"author_profile": "https://wordpress.stackexchange.com/users/33936",
"pm_score": 1,
"selected": false,
"text": "<p>query all posts in the post type and then get the meta keys from the posts e.g.</p>\n\n<p><strong>Not tested, may need some amendments</strong></p>\n\n<pre><code>$meta_fields = array();\n$the_query = new WP_Query( 'post_type=posttype' );\nif ( $the_query->have_posts() ) {\n while ( $the_query->have_posts() ) {\n $the_query->the_post();\n\n $meta_array = get_post_meta( get_the_ID() );\n foreach( $meta_array as $meta) {\n $meta_fields = $meta[];\n\n } \n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>You can then do whatever you want with the $meta_fields variable</p>\n"
},
{
"answer_id": 348601,
"author": "Rao Abid",
"author_id": 66242,
"author_profile": "https://wordpress.stackexchange.com/users/66242",
"pm_score": 2,
"selected": false,
"text": "<p>Answer by @Gareth Gillman definitely works but its an expensive query if we have hundreds of posts.</p>\n\n<p>The function below is less expensive and using the wp native function <a href=\"https://codex.wordpress.org/Function_Reference/get_post_custom_keys\" rel=\"nofollow noreferrer\">get_post_custom_keys()</a></p>\n\n<pre><code>if ( ! function_exists( 'us_get_meta_keys_for_post_type' ) ) :\n\n function us_get_meta_keys_for_post_type( $post_type, $sample_size = 5 ) {\n\n $meta_keys = array();\n $posts = get_posts( array( 'post_type' => $post_type, 'limit' => $sample_size ) );\n\n\n foreach ( $posts as $post ) {\n $post_meta_keys = get_post_custom_keys( $post->ID );\n $meta_keys = array_merge( $meta_keys, $post_meta_keys );\n }\n\n // Use array_unique to remove duplicate meta_keys that we received from all posts\n // Use array_values to reset the index of the array\n return array_values( array_unique( $meta_keys ) );\n\n }\n\nendif;\n</code></pre>\n\n<p>You may use the $sample_size param to include more posts in the loop.</p>\n\n<p>Hope it helps someone.</p>\n"
},
{
"answer_id": 402559,
"author": "pclalv",
"author_id": 219084,
"author_profile": "https://wordpress.stackexchange.com/users/219084",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that <a href=\"https://developer.wordpress.org/reference/functions/get_registered_meta_keys/\" rel=\"nofollow noreferrer\"><code>get_registered_meta_keys</code></a> will do the trick. Invoke it like this, <code>get_registered_meta_keys( 'post', $post_type )</code>, and it'll return an associative array of all of the meta keys and the data defines them. You can call <code>array_keys( get_registered_meta_keys( 'post', $post_type ) )</code> if you just want the keys.</p>\n<p>I think that this is correct because the source for <a href=\"https://developer.wordpress.org/reference/functions/register_post_meta/\" rel=\"nofollow noreferrer\"><code>register_post_meta</code></a> shows that it simply defines an <code>'object_subtype'</code> key and then delegates to <code>register_meta( 'post', $meta_key, $args )</code>. The <code>$object_type</code> arg and <code>object_subtype</code> key that are used in <code>register_meta</code> seem to line-up exactly with the args that <code>get_registered_meta_keys</code> accepts.</p>\n"
}
] |
2016/12/16
|
[
"https://wordpress.stackexchange.com/questions/249512",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109108/"
] |
I've got the opposite problem a lot of people can when switching servers. All the pages work fine, EXCEPT the home page, which is generating a 404. It's just the blog URL by itself (mysite.com/blogfolder/). Wordpress is installed in a folder in the site root, and worked fine at the old host. htaccess is all what it is supposed to be for this kind of installation. What could cause this??
|
Answer by @Gareth Gillman definitely works but its an expensive query if we have hundreds of posts.
The function below is less expensive and using the wp native function [get\_post\_custom\_keys()](https://codex.wordpress.org/Function_Reference/get_post_custom_keys)
```
if ( ! function_exists( 'us_get_meta_keys_for_post_type' ) ) :
function us_get_meta_keys_for_post_type( $post_type, $sample_size = 5 ) {
$meta_keys = array();
$posts = get_posts( array( 'post_type' => $post_type, 'limit' => $sample_size ) );
foreach ( $posts as $post ) {
$post_meta_keys = get_post_custom_keys( $post->ID );
$meta_keys = array_merge( $meta_keys, $post_meta_keys );
}
// Use array_unique to remove duplicate meta_keys that we received from all posts
// Use array_values to reset the index of the array
return array_values( array_unique( $meta_keys ) );
}
endif;
```
You may use the $sample\_size param to include more posts in the loop.
Hope it helps someone.
|
249,513 |
<p>I have a weird issue on <a href="https://meta-game.org/" rel="nofollow noreferrer">my site that's only affecting mobile</a>. If you scroll down past the black "What's Hot" section, you'll see the standard posts with featured images. Now, if you refresh the page, the standard posts after the "What's Hot" section are missing the featured images. Nothing shows up in the apache or wordpress logs, and if you browse in a private session, then the featured images appear. This leads me to believe it's a caching issue, but I don't know how to proceed from there.</p>
<p>Another side note, I really noticed this when I swapped over to HTTPS, and I'm serving mixed content (images over http, everything else over https for performance). Here are my rewrite rules from my .htaccess (I just ripped them from a tutorial):</p>
<pre><code># 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
</code></pre>
<p>I have verified that this is affecting Android 6.0.1 on a handful of devices, as well as some variations of iPhone. At this point, I really don't know how to proceed.</p>
|
[
{
"answer_id": 249695,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>The images there you load is always to big for teh view screen, as example this image - <code>https://meta-game.org/wp-content/uploads/2016/12/league_of_legends_world_championship_2015.0.0.jpg</code>, <em>1600 x 900 pixel</em>. As alternate for the mobile view is this image defined - <code>https://i2.wp.com/meta-game.org/wp-content/uploads/bfi_thumb/dummy-transparent-n019axwscfu441qfxjqwpodrdle9kgsyvjjtwpvhgo.png?zoom=2&resize=288%2C162</code>, but this is a transparent dummy. </p>\n\n<p>You should use for this usage a thumbnail with smaller size to load fast. Change your theme source to load a thumbnail of each image. Maybe you have function inside the <code>functions.php</code> of your theme, a settings options or much other chances for this definition. TO analyze this use an Webinspector inside a browser on a Desktop, like in Chrome - screenshot below.\n<a href=\"https://i.stack.imgur.com/C9b6p.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/C9b6p.png\" alt=\"enter image description here\"></a></p>\n\n<ul>\n<li>Also the hint. The question is to localized and without code is not really possible to solve the topic. Maybe you should ask the developer, the support team of this team to solve this solid.</li>\n</ul>\n"
},
{
"answer_id": 250036,
"author": "Adriano Monecchi",
"author_id": 45893,
"author_profile": "https://wordpress.stackexchange.com/users/45893",
"pm_score": -1,
"selected": false,
"text": "<p>I've accessed your website and it seems there's no issues with your post featured images, this leads me to think you might have solved it or it was just a caching issue as you've mentioned.</p>\n\n<hr>\n\n<h1>WordPress HTTPS</h1>\n\n<h3>Forcing All Pages to HTTPS</h3>\n\n<p>For ensuring everything else is loaded over <code>https</code>, make sure you change the site and home urls under <strong>Settings >> General</strong> in WordPress Admin. Make it read <strong>https:</strong>//meta-game.org - and then Save changes.</p>\n\n<p><a href=\"https://i.stack.imgur.com/MZnNh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MZnNh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Additionally, If you’re looking for a simple way to secure WordPress logins (the wp-login.php script) or the entire wp-admin area, you could set one the constant bellow in <code>wp-config.php</code>:</p>\n\n<p><code>define('FORCE_SSL_ADMIN', true);</code></p>\n\n<hr>\n\n<h3>Inspecting the mixed content sources</h3>\n\n<p>Regarding the mixed content being loaded from both the <code>http</code> and <code>https</code> protocols, I'd suggest you to inspect your theme's templates or even a plugin and search for anything hard-coded with <code>http</code> and then fix it.</p>\n\n<p>When developers are aware of this, it shouldn't be a problem, but some times a few themes come with the <code>http</code>protocol hard-coded within its templates, that's a bad practice I know, but we've got to fix it somehow.</p>\n\n<p>A pretty simple method for inspecting is to load the page via HTTPS, and then right-click anywhere on the page and click <em>“View Page Source”</em>, <em>“View Source”</em>, or <em>“Source”</em>, depending on your browser.</p>\n\n<p>Then use the “Find” command, <strong>Edit -> Find</strong> or <code>(Ctrl+F or Cmd+F)</code> and search for:</p>\n\n<p><code>src=\"http:</code>\n(with double-quote)</p>\n\n<p><code>src='http:</code>\n(with single-quote)</p>\n\n<p>Long story short, you’re manually looking for images, scripts, iframes, and all other assets served via HTTP instead of HTTPS.</p>\n\n<p>Make note of each item sourced via HTTP and you’ll get an idea where to find the problem. </p>\n\n<hr>\n\n<h3>Thoughts on fixing the mixed content</h3>\n\n<h3>Using Relative URLs</h3>\n\n<p>This is the simplest fix. If an asset (image, script, etc.) is hard-coded into a plugin or theme, change it from <code>http://example.com/assets/logo.png</code> to <code>//example.com/assets/logo.png</code>.</p>\n\n<p>Typically, this is most useful when including assets from other servers, like Google scripts, API scripts, or iframes.</p>\n\n<p>Before doing this, however, you need to make sure the HTTPS version is available. If loading an asset from a site that doesn’t have HTTPS enabled, it’s probably best to remove the reference entirely (i.e. comment out or delete) or to save the asset to your own server and change the source to load via your site instead.</p>\n\n<hr>\n\n<h3>Using Proper WordPress Coding Standards</h3>\n\n<p>A nice approach is to use the WP function <code>is_ssl()</code> to conditionally load assets in templates depending of the protocol that is being used by the website, e.g:</p>\n\n<p><code>$protocol = is_ssl() ? 'https:' : 'http:';</code></p>\n\n<p>Enqueueing an external content with the above method:</p>\n\n<p><strong>Instead of manually setting the protocol...</strong></p>\n\n<p><code>wp_enqueue_script('bootstrapjs', 'https://cdn.jsdelivr.net/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js', 'false', null, TRUE);</code></p>\n\n<p><strong>Let's do it dynamically</strong> </p>\n\n<p><code>wp_enqueue_script('bootstrapjs', $protocol.'//cdn.jsdelivr.net/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js', 'false', null, TRUE);</code></p>\n\n<p>Assuring your website does not serve mixed content, provides your visitors with a pleasant browsing experience, the described methods here should help you to keep your site on track while using ssl.</p>\n"
},
{
"answer_id": 250318,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": true,
"text": "<p><a href=\"https://i.stack.imgur.com/rweR4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rweR4.png\" alt=\"enter image description here\"></a></p>\n\n<p>The images not being loaded are prefixed with the domain <code>https://i2.wp.com</code> \nThis is the <a href=\"https://en.wikipedia.org/wiki/Content_delivery_network\" rel=\"nofollow noreferrer\">CDN</a> used when you activate the <strong>PHOTON module</strong> in the <a href=\"https://wordpress.org/plugins/jetpack/\" rel=\"nofollow noreferrer\"><strong>Jetpack Plugin</strong></a>.\nIf you deactivate the <strong>PHOTON module</strong> or deactivate the <a href=\"https://wordpress.org/plugins/jetpack/\" rel=\"nofollow noreferrer\"><strong>Jetpack Plugin</strong></a>, you should be rid of the issue.</p>\n"
}
] |
2016/12/16
|
[
"https://wordpress.stackexchange.com/questions/249513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107325/"
] |
I have a weird issue on [my site that's only affecting mobile](https://meta-game.org/). If you scroll down past the black "What's Hot" section, you'll see the standard posts with featured images. Now, if you refresh the page, the standard posts after the "What's Hot" section are missing the featured images. Nothing shows up in the apache or wordpress logs, and if you browse in a private session, then the featured images appear. This leads me to believe it's a caching issue, but I don't know how to proceed from there.
Another side note, I really noticed this when I swapped over to HTTPS, and I'm serving mixed content (images over http, everything else over https for performance). Here are my rewrite rules from my .htaccess (I just ripped them from a tutorial):
```
# 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
```
I have verified that this is affecting Android 6.0.1 on a handful of devices, as well as some variations of iPhone. At this point, I really don't know how to proceed.
|
[](https://i.stack.imgur.com/rweR4.png)
The images not being loaded are prefixed with the domain `https://i2.wp.com`
This is the [CDN](https://en.wikipedia.org/wiki/Content_delivery_network) used when you activate the **PHOTON module** in the [**Jetpack Plugin**](https://wordpress.org/plugins/jetpack/).
If you deactivate the **PHOTON module** or deactivate the [**Jetpack Plugin**](https://wordpress.org/plugins/jetpack/), you should be rid of the issue.
|
249,601 |
<p>I have a function I'm using to display a login notification when a user without access tries to view a single post. The function also displays the post excerpt publicly on archive, widgets, etc , but shows the login notification only when the full post is viewed, i.e. <code>is_singular</code></p>
<p>This basically allows users without access to view a snippet of the post on archive pages, but when they click & try to view the full post they're prompted with a notification to login or register. </p>
<p>The issue I'm having is that when using a related posts widget, the login notification is displayed when it shouldn't be. I'm pretty sure it has to do with how I'm defining the post variable in my function which is causing it to not differentiate between posts displayed as excerpts in the widget vs the full single post. Looking for some insight. </p>
<p><strong>Content Protection function:</strong> </p>
<pre><code>/*Show Excerpt for Protected Content*/
//Show mm content even if the user doesn't have access
function customContentProtection($data)
{
error_log('customContentProtection');
return true;
}
add_filter('mm_bypass_content_protection', 'customContentProtection');
//then we add the filters for the archive content
add_filter( 'the_content', 'sbm_mm_content_filter' );
function sbm_mm_content_filter( $content ) {
global $post;
global $post_id;
if ( !is_singular())
return $content;
$new_content = $content;
// define what users without access view
if ( mm_access_decision(array("access"=>"true")) != true ){
//Need to apply a filter to get the excerpt if the template doesn't include it
$new_content = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));
/*
//This is where we output the excerpt & login form
echo '<div>' . $new_content . '</div><br><div>' . do_shortcode('[mm-form-c form="red" url="/member-registration"]') .'</div>';
*/
//Instead of the excerpt let's output a blurred text image
$url = site_url();
echo
'<div class="no-access-wrapper">
<div class="no-access">
<img src=" ' . $url . '/wp-content/themes/splash-child/images/blurred-text.png"></div>
<div class="no-access-top">
<h3 style="text-align:center;">This content is for members only. Please login or sign up.</h3>
' . do_shortcode('[mm-form-c form="red" url="/member-registration"]') . '
<br>
<p style="text-align:center;"> If you are already logged in and are having trouble viewing this content, please <a href="mailto: [email protected]">contact support</a></p>
</div>
</div>';
}
else return $new_content;
}
</code></pre>
<p>Here's the section of my single.php file that outputs the related posts widget: </p>
<pre><code> <?php
}
$related_post_number = $bdp_settings['related_post_number'];
$col_class = '';
if ($related_post_number == 2) {
$post_perpage = 2;
}
if ($related_post_number == 3) {
$post_perpage = 3;
}
if ($related_post_number == 4) {
$post_perpage = 4;
}
$related_post_by = $bdp_settings['related_post_by'];
$title = $bdp_settings['related_post_title'];
if (isset($bdp_settings['display_related_post']) && $bdp_settings['display_related_post'] == 1) {
$related_post_content_length = isset($bdp_settings['related_post_content_length']) ? $bdp_settings['related_post_content_length'] : '';
$args = array();
if ($related_post_by == "category") {
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach ($categories as $individual_category)
$category_ids[] = $individual_category->term_id;
$args = array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => $post_perpage // Number of related posts that will be displayed. 'caller_get_posts' => 1,
);
}
} elseif ($related_post_by == "tag") {
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach ($tags as $individual_tag)
$tag_ids[] = $individual_tag->term_id;
$args = array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => $post_perpage // Number of related posts to display.
);
}
}
$my_query = new wp_query($args);
if ($my_query->have_posts()) {
?>
<div class="related_post_wrap">
<?php
do_action('bdp_related_post_detail', $theme, $post_perpage, $related_post_by, $title, $related_post_content_length);
?>
</div>
<?php
}
}
// If comments are open or we have at least one comment, load up the comment template.
if ($bdp_settings['display_comment'] == 1) {
if (comments_open() || get_comments_number()) {
comments_template();
}
}
// End of the loop.
endwhile;
if ($theme == "offer_blog" || $theme == "winter") {
echo '</div>';
}
?>
</div>
<?php do_action('bdp_after_single_page'); ?>
</main><!-- .site-main -->
</div><!-- .content-area -->
</code></pre>
|
[
{
"answer_id": 249594,
"author": "Rikki B",
"author_id": 109162,
"author_profile": "https://wordpress.stackexchange.com/users/109162",
"pm_score": 3,
"selected": true,
"text": "<p>It was a stupid question, I just realized, if I just create a custom shortcode for it, the plugin will not wrap it in <code><p></code> tags then, or even better still just create it as a plugin of it's own.</p>\n"
},
{
"answer_id": 249861,
"author": "kaosarch",
"author_id": 109322,
"author_profile": "https://wordpress.stackexchange.com/users/109322",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://codecanyon.net/item/woocommerce-amazon-affiliates-wordpress-plugin/3057503\" rel=\"nofollow noreferrer\">Have you considered using a plugin for the whole integration?</a> Not sure if you're doing something more customized than affiliate products though.</p>\n"
}
] |
2016/12/18
|
[
"https://wordpress.stackexchange.com/questions/249601",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109165/"
] |
I have a function I'm using to display a login notification when a user without access tries to view a single post. The function also displays the post excerpt publicly on archive, widgets, etc , but shows the login notification only when the full post is viewed, i.e. `is_singular`
This basically allows users without access to view a snippet of the post on archive pages, but when they click & try to view the full post they're prompted with a notification to login or register.
The issue I'm having is that when using a related posts widget, the login notification is displayed when it shouldn't be. I'm pretty sure it has to do with how I'm defining the post variable in my function which is causing it to not differentiate between posts displayed as excerpts in the widget vs the full single post. Looking for some insight.
**Content Protection function:**
```
/*Show Excerpt for Protected Content*/
//Show mm content even if the user doesn't have access
function customContentProtection($data)
{
error_log('customContentProtection');
return true;
}
add_filter('mm_bypass_content_protection', 'customContentProtection');
//then we add the filters for the archive content
add_filter( 'the_content', 'sbm_mm_content_filter' );
function sbm_mm_content_filter( $content ) {
global $post;
global $post_id;
if ( !is_singular())
return $content;
$new_content = $content;
// define what users without access view
if ( mm_access_decision(array("access"=>"true")) != true ){
//Need to apply a filter to get the excerpt if the template doesn't include it
$new_content = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));
/*
//This is where we output the excerpt & login form
echo '<div>' . $new_content . '</div><br><div>' . do_shortcode('[mm-form-c form="red" url="/member-registration"]') .'</div>';
*/
//Instead of the excerpt let's output a blurred text image
$url = site_url();
echo
'<div class="no-access-wrapper">
<div class="no-access">
<img src=" ' . $url . '/wp-content/themes/splash-child/images/blurred-text.png"></div>
<div class="no-access-top">
<h3 style="text-align:center;">This content is for members only. Please login or sign up.</h3>
' . do_shortcode('[mm-form-c form="red" url="/member-registration"]') . '
<br>
<p style="text-align:center;"> If you are already logged in and are having trouble viewing this content, please <a href="mailto: [email protected]">contact support</a></p>
</div>
</div>';
}
else return $new_content;
}
```
Here's the section of my single.php file that outputs the related posts widget:
```
<?php
}
$related_post_number = $bdp_settings['related_post_number'];
$col_class = '';
if ($related_post_number == 2) {
$post_perpage = 2;
}
if ($related_post_number == 3) {
$post_perpage = 3;
}
if ($related_post_number == 4) {
$post_perpage = 4;
}
$related_post_by = $bdp_settings['related_post_by'];
$title = $bdp_settings['related_post_title'];
if (isset($bdp_settings['display_related_post']) && $bdp_settings['display_related_post'] == 1) {
$related_post_content_length = isset($bdp_settings['related_post_content_length']) ? $bdp_settings['related_post_content_length'] : '';
$args = array();
if ($related_post_by == "category") {
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach ($categories as $individual_category)
$category_ids[] = $individual_category->term_id;
$args = array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => $post_perpage // Number of related posts that will be displayed. 'caller_get_posts' => 1,
);
}
} elseif ($related_post_by == "tag") {
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach ($tags as $individual_tag)
$tag_ids[] = $individual_tag->term_id;
$args = array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page' => $post_perpage // Number of related posts to display.
);
}
}
$my_query = new wp_query($args);
if ($my_query->have_posts()) {
?>
<div class="related_post_wrap">
<?php
do_action('bdp_related_post_detail', $theme, $post_perpage, $related_post_by, $title, $related_post_content_length);
?>
</div>
<?php
}
}
// If comments are open or we have at least one comment, load up the comment template.
if ($bdp_settings['display_comment'] == 1) {
if (comments_open() || get_comments_number()) {
comments_template();
}
}
// End of the loop.
endwhile;
if ($theme == "offer_blog" || $theme == "winter") {
echo '</div>';
}
?>
</div>
<?php do_action('bdp_after_single_page'); ?>
</main><!-- .site-main -->
</div><!-- .content-area -->
```
|
It was a stupid question, I just realized, if I just create a custom shortcode for it, the plugin will not wrap it in `<p>` tags then, or even better still just create it as a plugin of it's own.
|
249,612 |
<p>Want to use a different featured image size for a custom post type and exclude it from main blog loop. And also want to display it on specific page.</p>
<p>What will be the fastest way to achieve this? With code mess up and plugins?</p>
<p>Prefer a code snippet solution, but main issue it should work out-of-box, as fast solution is a priority.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 249618,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 1,
"selected": false,
"text": "<p>Make a custom post-type template with the specific featured size in the template or appropriate css applied to the image.</p>\n"
},
{
"answer_id": 249619,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 3,
"selected": true,
"text": "<p>This might help - <a href=\"https://wordpress.stackexchange.com/questions/32811/set-featured-image-size-for-a-custom-post-type?rq=1\">Set featured image size for a custom post type</a>, </p>\n\n<blockquote>\n <p>Just add a new image size</p>\n\n<pre><code>add_image_size( 'companies_thumb', 120, 120, true);\n</code></pre>\n \n <p>Then in the post type template for companies you just call the thumb\n you defined.</p>\n\n<pre><code><?php the_post_thumbnail('companies_thumb'); ?>\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 276687,
"author": "MadLandley",
"author_id": 92735,
"author_profile": "https://wordpress.stackexchange.com/users/92735",
"pm_score": 2,
"selected": false,
"text": "<p>I was also looking for a way to change the featured image size for a custom post type – even in the admin so you’ll se a correct preview when the image is inserted. This code will do the trick and hopefully this will help someone.</p>\n\n<p>Put the code in functions.php of your child theme.\nRemember that your theme must support post thumbnails.</p>\n\n<pre><code>// Change Featured Image Size for Custom Post Type\nfunction custom_post_type_featured_image_size() {\n add_post_type_support( 'your_custom_post_type', 'thumbnail' );\n set_post_thumbnail_size( width, height, true ); //true will crop image\n}\nadd_action( 'init', 'custom_post_type_featured_image_size' );\n</code></pre>\n"
}
] |
2016/12/18
|
[
"https://wordpress.stackexchange.com/questions/249612",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32880/"
] |
Want to use a different featured image size for a custom post type and exclude it from main blog loop. And also want to display it on specific page.
What will be the fastest way to achieve this? With code mess up and plugins?
Prefer a code snippet solution, but main issue it should work out-of-box, as fast solution is a priority.
Thanks in advance.
|
This might help - [Set featured image size for a custom post type](https://wordpress.stackexchange.com/questions/32811/set-featured-image-size-for-a-custom-post-type?rq=1),
>
> Just add a new image size
>
>
>
> ```
> add_image_size( 'companies_thumb', 120, 120, true);
>
> ```
>
> Then in the post type template for companies you just call the thumb
> you defined.
>
>
>
> ```
> <?php the_post_thumbnail('companies_thumb'); ?>
>
> ```
>
>
|
249,622 |
<p>How can I check if post with name for example Weather exists? If not I want to create it.</p>
<pre><code>function such_post_exists($title) {
global $wpdb;
$p_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
if ( !empty ( $title ) ) {
return (int) $wpdb->query("SELECT FROM $wpdb->posts WHERE post_title = $p_title");
}
return 0;
}
</code></pre>
|
[
{
"answer_id": 249624,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 4,
"selected": true,
"text": "<p>Wordpress has a <code>post_exists</code> function that returns the post ID or 0 otherwise.\nSo you can do</p>\n\n<pre><code>if ( 0 === post_exists( $title ) ) {\n **YOUR_CODE_HERE**\n}\n</code></pre>\n"
},
{
"answer_id": 328314,
"author": "samjco",
"author_id": 29133,
"author_profile": "https://wordpress.stackexchange.com/users/29133",
"pm_score": 1,
"selected": false,
"text": "<p>If Post does not exist, create it... IF it does exist, update it.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>\n$post_title = \"This Awesome Title\";\n$post_content = \"My content of something cool.\";\n$post_status = \"publish\"; //publish, draft, etc\n$post_type = \"page\"; // or whatever post type desired\n\n/* Attempt to find post id by post name if it exists */\n$found_post_title = get_page_by_title( $post_title, OBJECT, $post_type );\n$found_post_id = $found_post_title->ID;\n\n/**********************************************************\n** Check If Page does not exist, if true, create a new post \n************************************************************/\nif ( FALSE === get_post_status( $found_post_id ) ): \n\n $post_args = array(\n 'post_title' => $post_title,\n 'post_type' => $post_type,\n 'post_content'=> $post_content,\n 'post_status' => $post_status,\n //'post_author' => get_current_user_id(),\n\n /* If you have meta fields to enter data into */ \n 'meta_input' => array(\n 'meta_key1' => 'my value',\n 'meta_key2' => 'my other value',\n ),\n ); \n\n\n /* Add a new wp post into db, return it's post id */\n $returned_post_id = wp_insert_post( $post_args ); \n\n /* Update page template only if using \"page\" as the post_type */ \n update_post_meta( $returned_post_id, '_wp_page_template', 'my-page-template.php' ); \n\n /* Add values into meta fields. Work with ACF CUSTOM FIELDS!! */\n $field_key = \"My_Field_KEY\";\n $value = \"my custom value\";\n update_field( $field_key, $value, $returned_post_id );\n\n $field_key = \"My_Other_Field_KEY\";\n $value = \"my other custom value\";\n update_field( $field_key, $value, $returned_post_id );\n\n /* Save a checkbox or select value */\n // $field_key = \"My_Field_KEY\";\n // $value = array(\"red\", \"blue\", \"yellow\");\n // update_field( $field_key, $value, $returned_post_id );\n\n /* Save to a repeater field value */\n // $field_key = \"My_Field_KEY\";\n // $value = array(\n // array(\n // \"ss_name\" => \"Foo\",\n // \"ss_type\" => \"Bar\"\n // )\n // );\n // update_field( $field_key, $value, $returned_post_id );\n\n /* Echo a response! */\n echo \"<span class='pg-new'><strong>\". $post_title . \" Created!</strong></span><br>\";\n echo \"<a href='\".esc_url( get_permalink($returned_post_id) ).\"' target='_Blank'>\". $post_title . \"</a><p>\";\n\n\nelse: \n/***************************\n** IF POST EXISTS, update it \n****************************/\n\n /* Update post */\n $update_post_args = array(\n 'ID' => $found_post_id,\n 'post_title' => $post_title,\n 'post_content' => $post_content,\n );\n\n /* Update the post into the database */\n wp_update_post( $update_post_args );\n\n /* Update values into meta fields */\n $field_key = \"My_Field_KEY\";\n $value = \"my custom value\";\n update_field( $field_key, $value, $found_post_id );\n\n $field_key = \"My_Other_Field_KEY\";\n $value = \"my other custom value\";\n update_field( $field_key, $value, $found_post_id );\n\n /* Echo a response! */\n echo \"<span class='pg-update'><strong>\". $post_title . \" Updated!</strong></span><br>\"; \n echo \"<a href='\".esc_url( get_permalink($found_post_id) ).\"' target='_Blank'>View</a> | <a href='post.php?post=\".$found_post_id.\"&action=edit'>\". $post_title . \"</a><p>\";\n\nendif;\n\n</code></pre>\n"
}
] |
2016/12/18
|
[
"https://wordpress.stackexchange.com/questions/249622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105218/"
] |
How can I check if post with name for example Weather exists? If not I want to create it.
```
function such_post_exists($title) {
global $wpdb;
$p_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
if ( !empty ( $title ) ) {
return (int) $wpdb->query("SELECT FROM $wpdb->posts WHERE post_title = $p_title");
}
return 0;
}
```
|
Wordpress has a `post_exists` function that returns the post ID or 0 otherwise.
So you can do
```
if ( 0 === post_exists( $title ) ) {
**YOUR_CODE_HERE**
}
```
|
249,630 |
<p>This,</p>
<pre><code>if( has_term( 'jazz', 'genre' ) ) {
// do something
}
</code></pre>
<p>will check if a post has the term <code>jazz</code> from the custom taxonomy <code>genre</code>. But how to check if a post belongs to a custom taxonomy <code>genre</code>? No matter whatever term it has, as long as it has something from the <code>genre</code> taxonomy, it will check.</p>
<p>So something like this,</p>
<pre><code>if ( has_taxonomy('genre') ) {
// whether it's jazz, blues, rock and roll; doesn't matter as long as the post has any of them.
}
</code></pre>
|
[
{
"answer_id": 249634,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<pre><code>if ( has_term('', 'genre') ) {\n // whether it's jazz, blues, rock and roll; doesn't matter as long as the post has any of them.\n}\n</code></pre>\n\n<p>would return true if the post contains any term in the <em>genre</em> taxonomy</p>\n"
},
{
"answer_id": 249635,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>You can have the term input empty, e.g.</p>\n\n<pre><code>if( has_term( '', 'genre' ) ) {\n // do something\n}\n</code></pre>\n\n<p>to see if the current post object has any terms in the genre taxonomy.</p>\n\n<p>It uses <a href=\"https://developer.wordpress.org/reference/functions/is_object_in_term/\" rel=\"noreferrer\"><code>is_object_in_term()</code></a> where:</p>\n\n<blockquote>\n <p>The given terms are checked against the object’s terms’ term_ids,\n names and slugs. Terms given as integers will only be checked against\n the object’s terms’ term_ids. If no terms are given, determines if\n object is associated with any terms in the given taxonomy.</p>\n</blockquote>\n"
}
] |
2016/12/18
|
[
"https://wordpress.stackexchange.com/questions/249630",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13291/"
] |
This,
```
if( has_term( 'jazz', 'genre' ) ) {
// do something
}
```
will check if a post has the term `jazz` from the custom taxonomy `genre`. But how to check if a post belongs to a custom taxonomy `genre`? No matter whatever term it has, as long as it has something from the `genre` taxonomy, it will check.
So something like this,
```
if ( has_taxonomy('genre') ) {
// whether it's jazz, blues, rock and roll; doesn't matter as long as the post has any of them.
}
```
|
You can have the term input empty, e.g.
```
if( has_term( '', 'genre' ) ) {
// do something
}
```
to see if the current post object has any terms in the genre taxonomy.
It uses [`is_object_in_term()`](https://developer.wordpress.org/reference/functions/is_object_in_term/) where:
>
> The given terms are checked against the object’s terms’ term\_ids,
> names and slugs. Terms given as integers will only be checked against
> the object’s terms’ term\_ids. If no terms are given, determines if
> object is associated with any terms in the given taxonomy.
>
>
>
|
249,670 |
<p>I'm trying to check the output of a variable in my functions.php file that runs after a new woocommerce order. The code will get the order time from a new order and store it in a variable for me to use elsewhere the code being:</p>
<pre><code>$meeting_time = wc_get_order_item_meta($order_id, 'Time');
print_r($meeting_time);
</code></pre>
<p>I've tried a few ways to print the information:</p>
<ul>
<li>print_r </li>
<li>javascript popup box</li>
<li>writing to error log</li>
</ul>
<p>but I can't seem to get any of these to work as my php knowledge isn't very good.</p>
<p>I want to be able to see the output of the variable to make sure it's returning what I want.</p>
<p>Is anyone able to assist me?</p>
<p>Please and thankyou.</p>
|
[
{
"answer_id": 249672,
"author": "TCode",
"author_id": 109129,
"author_profile": "https://wordpress.stackexchange.com/users/109129",
"pm_score": 0,
"selected": false,
"text": "<p>wc_get_order_item_meta function requires an Order Item's ID, not the Order ID.</p>\n\n<pre><code>wc_get_order_item_meta($item_id, $key, $single );\n</code></pre>\n\n<p>Because all orders are stored as posts, you can get the post datetime from the order ID, and use that instead.</p>\n\n<pre><code>$order = get_post($orderID);\n$order_time = $order->post_date;\n</code></pre>\n\n<p>then you can print that out using:</p>\n\n<pre><code>print_r($order_time);\n</code></pre>\n"
},
{
"answer_id": 249682,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://php.net/manual/en/function.var-dump.php\" rel=\"nofollow noreferrer\"><code>var_dump()</code></a> instead of <code>print_r()</code> - you get the type and the value of the variable and it will also work when your variable holds <code>FALSE</code> or <code>NULL</code>. </p>\n\n<pre><code>print_r( false ); # doesn't output anything\nvar_dump( false ); # output: bool(false)\n\nprint_r( NULL ); # doesn't output anything\nvar_dump( NULL ); # output: NULL\n</code></pre>\n\n<p>If you have arrays or objects to inspect, you could use a plugin like <a href=\"https://wordpress.org/plugins/kint-debugger/\" rel=\"nofollow noreferrer\">Kint Debugger</a> to format the output into a more readable format.</p>\n"
}
] |
2016/12/19
|
[
"https://wordpress.stackexchange.com/questions/249670",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107852/"
] |
I'm trying to check the output of a variable in my functions.php file that runs after a new woocommerce order. The code will get the order time from a new order and store it in a variable for me to use elsewhere the code being:
```
$meeting_time = wc_get_order_item_meta($order_id, 'Time');
print_r($meeting_time);
```
I've tried a few ways to print the information:
* print\_r
* javascript popup box
* writing to error log
but I can't seem to get any of these to work as my php knowledge isn't very good.
I want to be able to see the output of the variable to make sure it's returning what I want.
Is anyone able to assist me?
Please and thankyou.
|
You can use [`var_dump()`](http://php.net/manual/en/function.var-dump.php) instead of `print_r()` - you get the type and the value of the variable and it will also work when your variable holds `FALSE` or `NULL`.
```
print_r( false ); # doesn't output anything
var_dump( false ); # output: bool(false)
print_r( NULL ); # doesn't output anything
var_dump( NULL ); # output: NULL
```
If you have arrays or objects to inspect, you could use a plugin like [Kint Debugger](https://wordpress.org/plugins/kint-debugger/) to format the output into a more readable format.
|
249,671 |
<p>Very basic question, but I couldn't find an answer.</p>
<p>I am using the WP CLI post get command: <a href="https://wp-cli.org/commands/post/get/" rel="nofollow noreferrer">https://wp-cli.org/commands/post/get/</a></p>
<p>One of the option is [--field=], but I can't find in the doc the list of allowed values for this field.</p>
<p>What am I missing?</p>
|
[
{
"answer_id": 249681,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 3,
"selected": true,
"text": "<p>The list of fields is available on the <a href=\"https://wp-cli.org/commands/post/list/#available-fields\" rel=\"nofollow noreferrer\"><code>wp post list</code></a> page.</p>\n\n<blockquote>\n <p>These fields will be displayed by default for each post:</p>\n\n<pre><code>ID\npost_title\npost_name\npost_date\npost_status\n</code></pre>\n \n <p>These fields are optionally available:</p>\n\n<pre><code>post_author\npost_date_gmt\npost_content\npost_excerpt\ncomment_status\nping_status\npost_password\nto_ping\npinged\npost_modified\npost_modified_gmt\npost_content_filtered\npost_parent\nguid\nmenu_order\npost_type\npost_mime_type\ncomment_count\nfilter\nurl\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 364777,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 0,
"selected": false,
"text": "<p>Right, I think you have not see example section or the example section is available now.</p>\n\n<p>If you want to display only one field then you can use <code>--field</code> parameter.</p>\n\n<p>E.g</p>\n\n<pre><code>wp post list --field=ID\n</code></pre>\n\n<p>And to get multiple fields then you can use <code>--fields</code> parameter.</p>\n\n<p>E.g.</p>\n\n<pre><code>wp post list --fields=post_title,post_status\n</code></pre>\n\n<p><code>--field</code> is associated argument. Read more about the associate arguments at <a href=\"https://wp.me/p4Ams0-1g1\" rel=\"nofollow noreferrer\">https://wp.me/p4Ams0-1g1</a></p>\n"
}
] |
2016/12/19
|
[
"https://wordpress.stackexchange.com/questions/249671",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44388/"
] |
Very basic question, but I couldn't find an answer.
I am using the WP CLI post get command: <https://wp-cli.org/commands/post/get/>
One of the option is [--field=], but I can't find in the doc the list of allowed values for this field.
What am I missing?
|
The list of fields is available on the [`wp post list`](https://wp-cli.org/commands/post/list/#available-fields) page.
>
> These fields will be displayed by default for each post:
>
>
>
> ```
> ID
> post_title
> post_name
> post_date
> post_status
>
> ```
>
> These fields are optionally available:
>
>
>
> ```
> post_author
> post_date_gmt
> post_content
> post_excerpt
> comment_status
> ping_status
> post_password
> to_ping
> pinged
> post_modified
> post_modified_gmt
> post_content_filtered
> post_parent
> guid
> menu_order
> post_type
> post_mime_type
> comment_count
> filter
> url
>
> ```
>
>
|
249,677 |
<p>I use Wordpress 4.7 and I installed an accessibility module. This module requires pasting the following php code block before the body. I went through the mother-theme php files but didn't find something like html.php or html.tpl ... Should this file be created (and maybe also declared) somewhere?</p>
<pre><code><?php if(function_exists('acp_toolbar') ) { acp_toolbar(); }?>
</code></pre>
|
[
{
"answer_id": 249687,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 3,
"selected": true,
"text": "<p>You should paste that code in the header.php file. Just before the closing code . And that should be done. And if it is asking for pasting the code in the template then find the specific page where you want to place it. There may be different template for different page.</p>\n"
},
{
"answer_id": 249743,
"author": "Eric Malcolm",
"author_id": 109243,
"author_profile": "https://wordpress.stackexchange.com/users/109243",
"pm_score": 0,
"selected": false,
"text": "<p>Consider creating a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a> for custom changes, when you update your theme it will likely break. Besides that, Md. Amanur Rahman is correct, and so is Patrik Alienus.</p>\n"
}
] |
2016/12/19
|
[
"https://wordpress.stackexchange.com/questions/249677",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
I use Wordpress 4.7 and I installed an accessibility module. This module requires pasting the following php code block before the body. I went through the mother-theme php files but didn't find something like html.php or html.tpl ... Should this file be created (and maybe also declared) somewhere?
```
<?php if(function_exists('acp_toolbar') ) { acp_toolbar(); }?>
```
|
You should paste that code in the header.php file. Just before the closing code . And that should be done. And if it is asking for pasting the code in the template then find the specific page where you want to place it. There may be different template for different page.
|
249,697 |
<p>I want to display a loop in my page-projets.php file.</p>
<pre><code><div class="loop center">
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part('content');
endwhile;
get_template_part('pagination');
endif; ?>
</div>
</code></pre>
<p>However, on the resulting page, I can only see the page itself within the loop. Sometimes, it even returns a blank result : <a href="http://riehling.mrcoolblog.com/projets/" rel="nofollow noreferrer">http://riehling.mrcoolblog.com/projets/</a></p>
<p>Could you please tell me what's wrong here ?</p>
<p>Regards,
Greg</p>
|
[
{
"answer_id": 249687,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 3,
"selected": true,
"text": "<p>You should paste that code in the header.php file. Just before the closing code . And that should be done. And if it is asking for pasting the code in the template then find the specific page where you want to place it. There may be different template for different page.</p>\n"
},
{
"answer_id": 249743,
"author": "Eric Malcolm",
"author_id": 109243,
"author_profile": "https://wordpress.stackexchange.com/users/109243",
"pm_score": 0,
"selected": false,
"text": "<p>Consider creating a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a> for custom changes, when you update your theme it will likely break. Besides that, Md. Amanur Rahman is correct, and so is Patrik Alienus.</p>\n"
}
] |
2016/12/19
|
[
"https://wordpress.stackexchange.com/questions/249697",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88389/"
] |
I want to display a loop in my page-projets.php file.
```
<div class="loop center">
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part('content');
endwhile;
get_template_part('pagination');
endif; ?>
</div>
```
However, on the resulting page, I can only see the page itself within the loop. Sometimes, it even returns a blank result : <http://riehling.mrcoolblog.com/projets/>
Could you please tell me what's wrong here ?
Regards,
Greg
|
You should paste that code in the header.php file. Just before the closing code . And that should be done. And if it is asking for pasting the code in the template then find the specific page where you want to place it. There may be different template for different page.
|
249,707 |
<p>Something really weird happened. I want to change the color of this text but the index file has an !important there and when i change the color on my style.css file it doesn't work. What can i do to over ride that !important.</p>
<p>This is how it looks in my css file</p>
<pre><code>h1.entry-title {
color: #9A7B5C ;
}
</code></pre>
<p>i want that brown color but the index file isn't letting me change it from yellow. Please help and this how the index file looks like </p>
<pre><code>DIV SECTION DIV.container NAV A, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry HEADER.entry-header H1.entry-title, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry DIV.entry-content P, DIV P STRONG EM A, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry DIV.entry-content P.ui-draggable.ui-draggable-handle {
color: #ffe206 !important; }
</code></pre>
|
[
{
"answer_id": 249687,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 3,
"selected": true,
"text": "<p>You should paste that code in the header.php file. Just before the closing code . And that should be done. And if it is asking for pasting the code in the template then find the specific page where you want to place it. There may be different template for different page.</p>\n"
},
{
"answer_id": 249743,
"author": "Eric Malcolm",
"author_id": 109243,
"author_profile": "https://wordpress.stackexchange.com/users/109243",
"pm_score": 0,
"selected": false,
"text": "<p>Consider creating a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a> for custom changes, when you update your theme it will likely break. Besides that, Md. Amanur Rahman is correct, and so is Patrik Alienus.</p>\n"
}
] |
2016/12/19
|
[
"https://wordpress.stackexchange.com/questions/249707",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109224/"
] |
Something really weird happened. I want to change the color of this text but the index file has an !important there and when i change the color on my style.css file it doesn't work. What can i do to over ride that !important.
This is how it looks in my css file
```
h1.entry-title {
color: #9A7B5C ;
}
```
i want that brown color but the index file isn't letting me change it from yellow. Please help and this how the index file looks like
```
DIV SECTION DIV.container NAV A, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry HEADER.entry-header H1.entry-title, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry DIV.entry-content P, DIV P STRONG EM A, DIV DIV ARTICLE.post-860.page.type-page.status-publish.hentry DIV.entry-content P.ui-draggable.ui-draggable-handle {
color: #ffe206 !important; }
```
|
You should paste that code in the header.php file. Just before the closing code . And that should be done. And if it is asking for pasting the code in the template then find the specific page where you want to place it. There may be different template for different page.
|
249,712 |
<p>I originally made <a href="https://wordpress.stackexchange.com/questions/249357/ninja-forms-shortcode-not-producing-intended-results-in-custom-wordpress-theme">this post</a>, thinking that my problem was specific to the Ninja Forms plugin (the original post was obviously put on hold, for being off-topic). My reason for thinking so, was that WordPress' native gallery shortcode was working correctly, but it would seem that the issue affects <strong>all</strong> plugin shortcodes.</p>
<p>As this is no longer an issue with a specific plugin, but WordPress's ability to execute plugin shortcodes -- --, I've taken the liberty to assume that it is now considered on-topic.</p>
<p>Even with an empty <em>functions.php</em> file and the following as my only code, the issue still persists.</p>
<pre><code><?php
if (have_posts()) : while (have_posts()) : the_post();
the_content();
endwhile;
endif;
?>
</code></pre>
<p>When inspecting the page, this appears to output <strong>some</strong> of what it's supposed to, in the form of a script or div, but it's as if the plugins are never rendered, despite being initialized.</p>
<p>I've been stuck here for a few days now, so if anyone could give me a push in the right direction, that would be amazing!</p>
<p><strong>Note:</strong> I apologize if this is still considered to be off-topic. In case it is, please disregard this post.</p>
|
[
{
"answer_id": 249731,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 0,
"selected": false,
"text": "<p>You should try to active the default wordpress theme like twenty eleven or like that and then see if the problem persist ?</p>\n\n<p>If it is still there can you show a URL of your site so that I can have a look at it. Also please add the shortcode in that page which URL you are sharing with me.</p>\n"
},
{
"answer_id": 249801,
"author": "WPNoob",
"author_id": 109018,
"author_profile": "https://wordpress.stackexchange.com/users/109018",
"pm_score": 1,
"selected": false,
"text": "<p>As was pointed out by <a href=\"https://wordpress.stackexchange.com/users/4884/michael\">Michael</a>, I had been missing the <code>wp_head()</code> and <code>wp_footer()</code> functions.</p>\n\n<p>To anyone who might be in the same boat as I, you can have a look at the function references <a href=\"https://codex.wordpress.org/Function_Reference/wp_head\" rel=\"nofollow noreferrer\">here (head)</a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_footer\" rel=\"nofollow noreferrer\">here (footer)</a>.</p>\n\n<p>Thank you, to anyone who took their time to help me out, even if all they did was read the question. I'm glad we reached a conclusion so quickly!</p>\n"
}
] |
2016/12/19
|
[
"https://wordpress.stackexchange.com/questions/249712",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109018/"
] |
I originally made [this post](https://wordpress.stackexchange.com/questions/249357/ninja-forms-shortcode-not-producing-intended-results-in-custom-wordpress-theme), thinking that my problem was specific to the Ninja Forms plugin (the original post was obviously put on hold, for being off-topic). My reason for thinking so, was that WordPress' native gallery shortcode was working correctly, but it would seem that the issue affects **all** plugin shortcodes.
As this is no longer an issue with a specific plugin, but WordPress's ability to execute plugin shortcodes -- --, I've taken the liberty to assume that it is now considered on-topic.
Even with an empty *functions.php* file and the following as my only code, the issue still persists.
```
<?php
if (have_posts()) : while (have_posts()) : the_post();
the_content();
endwhile;
endif;
?>
```
When inspecting the page, this appears to output **some** of what it's supposed to, in the form of a script or div, but it's as if the plugins are never rendered, despite being initialized.
I've been stuck here for a few days now, so if anyone could give me a push in the right direction, that would be amazing!
**Note:** I apologize if this is still considered to be off-topic. In case it is, please disregard this post.
|
As was pointed out by [Michael](https://wordpress.stackexchange.com/users/4884/michael), I had been missing the `wp_head()` and `wp_footer()` functions.
To anyone who might be in the same boat as I, you can have a look at the function references [here (head)](https://codex.wordpress.org/Function_Reference/wp_head) and [here (footer)](https://codex.wordpress.org/Function_Reference/wp_footer).
Thank you, to anyone who took their time to help me out, even if all they did was read the question. I'm glad we reached a conclusion so quickly!
|
249,744 |
<p>Brand new site. Not MU. No matter what I do, I cannot get a file uploaded that exceeds 2MB. I'm running a localhost server with WordPress 4.3.1</p>
<p>I've modified both relevant settings in the the site's <code>php.ini</code> as:</p>
<pre><code>upload_max_filesize = 64M
post_max_size = 64M
</code></pre>
<p>However, I'm still getting the message when trying to upload a plugin that's 2.5M</p>
<blockquote>
<p>The uploaded file exceeds the upload_max_filesize directive in
php.ini.</p>
</blockquote>
<p>Also, when I go to "Media > Add New", I get the message:</p>
<blockquote>
<p>Maximum upload file size: 2 MB.</p>
</blockquote>
<p>My htaccess file is the default and has no mention of max upload size.</p>
<p>What gives? Is it a requirement to restart anything after modifying the site's php.ini? If so, I could not find a restart command on my phpmyadmin panel.</p>
|
[
{
"answer_id": 249737,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": true,
"text": "<p>While I know version control approach to be used in practice, I don't think it's too common. WP has weak version control practices in general, so development of extensions doesn't quite plan for such.</p>\n\n<p>Example of specific scenario which will cause issues might be changes in template hierarchy. Let's say you customized <code>single.php</code> in version control. Then upstream theme rearranged things and got rid of <code>single.php</code> altogether in favor of more generic <code>singular.php</code>. Suddenly your changes hang in the air without template to apply them to, essentially your merge is blocked and you have to re-develop your changes on top of a new situation.</p>\n\n<p>With child theme your template will stay in place and continue to work, although occasional updates will be required in some cases as well.</p>\n\n<p>In a nutshell I would consider version control to be essentially a <em>fork</em> to maintain, while child theme would be a downstream extension (under your full control) with upstream <em>dependency</em>.</p>\n\n<p>In my subjective opinion maintaining a fork would be harder on resources in most cases. I would reserve it to solutions which <em>cannot</em> be achieved with a child theme.</p>\n"
},
{
"answer_id": 250234,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>If you plan to sell your theme later, I would go with the git.\nIt is up to you how you will organize yourself to work with the git.</p>\n\n<p>What I know creating new branches in git is a breeze, and you should create them often because branches are resource friendly.</p>\n\n<p>Every tutorial, I watched said feel free to create new branches.</p>\n\n<p>If you compare the child theme vs. the parent theme...\nI would ask you what do you think is a bit faster?</p>\n\n<p>In general, the answer is obvious since the child theme also executes the parent theme files.</p>\n\n<p>I would go with the parent theme and with creating the branches often.</p>\n"
}
] |
2016/12/19
|
[
"https://wordpress.stackexchange.com/questions/249744",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/366/"
] |
Brand new site. Not MU. No matter what I do, I cannot get a file uploaded that exceeds 2MB. I'm running a localhost server with WordPress 4.3.1
I've modified both relevant settings in the the site's `php.ini` as:
```
upload_max_filesize = 64M
post_max_size = 64M
```
However, I'm still getting the message when trying to upload a plugin that's 2.5M
>
> The uploaded file exceeds the upload\_max\_filesize directive in
> php.ini.
>
>
>
Also, when I go to "Media > Add New", I get the message:
>
> Maximum upload file size: 2 MB.
>
>
>
My htaccess file is the default and has no mention of max upload size.
What gives? Is it a requirement to restart anything after modifying the site's php.ini? If so, I could not find a restart command on my phpmyadmin panel.
|
While I know version control approach to be used in practice, I don't think it's too common. WP has weak version control practices in general, so development of extensions doesn't quite plan for such.
Example of specific scenario which will cause issues might be changes in template hierarchy. Let's say you customized `single.php` in version control. Then upstream theme rearranged things and got rid of `single.php` altogether in favor of more generic `singular.php`. Suddenly your changes hang in the air without template to apply them to, essentially your merge is blocked and you have to re-develop your changes on top of a new situation.
With child theme your template will stay in place and continue to work, although occasional updates will be required in some cases as well.
In a nutshell I would consider version control to be essentially a *fork* to maintain, while child theme would be a downstream extension (under your full control) with upstream *dependency*.
In my subjective opinion maintaining a fork would be harder on resources in most cases. I would reserve it to solutions which *cannot* be achieved with a child theme.
|
249,753 |
<p>I am using the REST API to publish posts outside of WordPress, and have run into a problem where not all of my shortcodes are getting processed. Specifically, most of my plugins' shortcodes are getting processed but nothing from visual composer is getting converted to HTML. I find that if I var_dump my REST API's post data function on the front end of the WordPress site itself (blank theme, theme is literally 'var_dump this function'), the shortcodes for VC do get processed.</p>
<p>I am not sure what I am doing wrong here, but here is my code for the REST API return:</p>
<pre><code>function return_page_single( WP_REST_Request $request ) {
$page_id = $request->get_param( 'page' );
$args = array(
'id' => $page_id,
'post_type' => 'page',
'posts_per_page' => 1
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
$page = $query->posts;
$page_content = $page[0]->post_content;
$page_content = apply_filters( 'the_content', $page_content );
$page_content = do_shortcode( $page_content );
$page[0]->post_content = $page_content;
$query_return['page'] = $page;
$query_return['query'] = $query->query;
}
wp_reset_postdata();
return $query_return;
}
</code></pre>
<p>If I dump the contents of my REST API result, I get shortcodes for VC but everything else processes.</p>
<p>If I place the following in my theme: </p>
<pre><code>var_dump( return_page_single( $request ) );
</code></pre>
<p>I get the fully processed post content.</p>
<p>I don't have a live example as this is being developed internally but if it helps to troubleshoot I can probably set something up.</p>
|
[
{
"answer_id": 249737,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": true,
"text": "<p>While I know version control approach to be used in practice, I don't think it's too common. WP has weak version control practices in general, so development of extensions doesn't quite plan for such.</p>\n\n<p>Example of specific scenario which will cause issues might be changes in template hierarchy. Let's say you customized <code>single.php</code> in version control. Then upstream theme rearranged things and got rid of <code>single.php</code> altogether in favor of more generic <code>singular.php</code>. Suddenly your changes hang in the air without template to apply them to, essentially your merge is blocked and you have to re-develop your changes on top of a new situation.</p>\n\n<p>With child theme your template will stay in place and continue to work, although occasional updates will be required in some cases as well.</p>\n\n<p>In a nutshell I would consider version control to be essentially a <em>fork</em> to maintain, while child theme would be a downstream extension (under your full control) with upstream <em>dependency</em>.</p>\n\n<p>In my subjective opinion maintaining a fork would be harder on resources in most cases. I would reserve it to solutions which <em>cannot</em> be achieved with a child theme.</p>\n"
},
{
"answer_id": 250234,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>If you plan to sell your theme later, I would go with the git.\nIt is up to you how you will organize yourself to work with the git.</p>\n\n<p>What I know creating new branches in git is a breeze, and you should create them often because branches are resource friendly.</p>\n\n<p>Every tutorial, I watched said feel free to create new branches.</p>\n\n<p>If you compare the child theme vs. the parent theme...\nI would ask you what do you think is a bit faster?</p>\n\n<p>In general, the answer is obvious since the child theme also executes the parent theme files.</p>\n\n<p>I would go with the parent theme and with creating the branches often.</p>\n"
}
] |
2016/12/19
|
[
"https://wordpress.stackexchange.com/questions/249753",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109253/"
] |
I am using the REST API to publish posts outside of WordPress, and have run into a problem where not all of my shortcodes are getting processed. Specifically, most of my plugins' shortcodes are getting processed but nothing from visual composer is getting converted to HTML. I find that if I var\_dump my REST API's post data function on the front end of the WordPress site itself (blank theme, theme is literally 'var\_dump this function'), the shortcodes for VC do get processed.
I am not sure what I am doing wrong here, but here is my code for the REST API return:
```
function return_page_single( WP_REST_Request $request ) {
$page_id = $request->get_param( 'page' );
$args = array(
'id' => $page_id,
'post_type' => 'page',
'posts_per_page' => 1
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
$page = $query->posts;
$page_content = $page[0]->post_content;
$page_content = apply_filters( 'the_content', $page_content );
$page_content = do_shortcode( $page_content );
$page[0]->post_content = $page_content;
$query_return['page'] = $page;
$query_return['query'] = $query->query;
}
wp_reset_postdata();
return $query_return;
}
```
If I dump the contents of my REST API result, I get shortcodes for VC but everything else processes.
If I place the following in my theme:
```
var_dump( return_page_single( $request ) );
```
I get the fully processed post content.
I don't have a live example as this is being developed internally but if it helps to troubleshoot I can probably set something up.
|
While I know version control approach to be used in practice, I don't think it's too common. WP has weak version control practices in general, so development of extensions doesn't quite plan for such.
Example of specific scenario which will cause issues might be changes in template hierarchy. Let's say you customized `single.php` in version control. Then upstream theme rearranged things and got rid of `single.php` altogether in favor of more generic `singular.php`. Suddenly your changes hang in the air without template to apply them to, essentially your merge is blocked and you have to re-develop your changes on top of a new situation.
With child theme your template will stay in place and continue to work, although occasional updates will be required in some cases as well.
In a nutshell I would consider version control to be essentially a *fork* to maintain, while child theme would be a downstream extension (under your full control) with upstream *dependency*.
In my subjective opinion maintaining a fork would be harder on resources in most cases. I would reserve it to solutions which *cannot* be achieved with a child theme.
|
249,761 |
<p>I have create a form on a wordpress page, and I'm trying to pass the values of the form to a php page, so I can send an email with that information, but I don't know how to create the php page, in what folder do I have to save the page.</p>
<p>Thank you (fist time using wordpress);</p>
<p>This is my form:
And I have a different page(send-email) that will collect the data. </p>
<p>I know how to do the code for the send-email page..I just nee dto know where to save the php page.</p>
<pre><code><form method="get" action="send-email.php" name="emailForm" onsubmit="return validate()">
<div class="form-group">
<label for="name">Name<span id="req">*</span></label><br>
<input type="text" class="form-control" id="name" name="name" placeholder="Quantum Management" value="">
</div>
<div class="form-group">
<label for="tel">Phone Number<span id="reqTel">*</span></label><br>
<input type="text" class="form-control" id="tel" name="tel" placeholder="(999) 123-4567" value="" >
</div>
<div class="form-group">
<label for="email">Email<span id="reqEmail">*</span></label><br>
<input type="text" class="form-control" id="email" name="email" placeholder="[email protected]" value="" >
</div>
<div class="form-group">
<label for="questions">Questions<span id="reqQuest">*</span></label><br>
<textarea class="form-control" rows="7" cols="8" id="questions" name="questions" placeholder="Questions" ></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" name="submit" value="yes">Submit</button>
</div>
</form>
</code></pre>
|
[
{
"answer_id": 249737,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 3,
"selected": true,
"text": "<p>While I know version control approach to be used in practice, I don't think it's too common. WP has weak version control practices in general, so development of extensions doesn't quite plan for such.</p>\n\n<p>Example of specific scenario which will cause issues might be changes in template hierarchy. Let's say you customized <code>single.php</code> in version control. Then upstream theme rearranged things and got rid of <code>single.php</code> altogether in favor of more generic <code>singular.php</code>. Suddenly your changes hang in the air without template to apply them to, essentially your merge is blocked and you have to re-develop your changes on top of a new situation.</p>\n\n<p>With child theme your template will stay in place and continue to work, although occasional updates will be required in some cases as well.</p>\n\n<p>In a nutshell I would consider version control to be essentially a <em>fork</em> to maintain, while child theme would be a downstream extension (under your full control) with upstream <em>dependency</em>.</p>\n\n<p>In my subjective opinion maintaining a fork would be harder on resources in most cases. I would reserve it to solutions which <em>cannot</em> be achieved with a child theme.</p>\n"
},
{
"answer_id": 250234,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 1,
"selected": false,
"text": "<p>If you plan to sell your theme later, I would go with the git.\nIt is up to you how you will organize yourself to work with the git.</p>\n\n<p>What I know creating new branches in git is a breeze, and you should create them often because branches are resource friendly.</p>\n\n<p>Every tutorial, I watched said feel free to create new branches.</p>\n\n<p>If you compare the child theme vs. the parent theme...\nI would ask you what do you think is a bit faster?</p>\n\n<p>In general, the answer is obvious since the child theme also executes the parent theme files.</p>\n\n<p>I would go with the parent theme and with creating the branches often.</p>\n"
}
] |
2016/12/19
|
[
"https://wordpress.stackexchange.com/questions/249761",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109259/"
] |
I have create a form on a wordpress page, and I'm trying to pass the values of the form to a php page, so I can send an email with that information, but I don't know how to create the php page, in what folder do I have to save the page.
Thank you (fist time using wordpress);
This is my form:
And I have a different page(send-email) that will collect the data.
I know how to do the code for the send-email page..I just nee dto know where to save the php page.
```
<form method="get" action="send-email.php" name="emailForm" onsubmit="return validate()">
<div class="form-group">
<label for="name">Name<span id="req">*</span></label><br>
<input type="text" class="form-control" id="name" name="name" placeholder="Quantum Management" value="">
</div>
<div class="form-group">
<label for="tel">Phone Number<span id="reqTel">*</span></label><br>
<input type="text" class="form-control" id="tel" name="tel" placeholder="(999) 123-4567" value="" >
</div>
<div class="form-group">
<label for="email">Email<span id="reqEmail">*</span></label><br>
<input type="text" class="form-control" id="email" name="email" placeholder="[email protected]" value="" >
</div>
<div class="form-group">
<label for="questions">Questions<span id="reqQuest">*</span></label><br>
<textarea class="form-control" rows="7" cols="8" id="questions" name="questions" placeholder="Questions" ></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" name="submit" value="yes">Submit</button>
</div>
</form>
```
|
While I know version control approach to be used in practice, I don't think it's too common. WP has weak version control practices in general, so development of extensions doesn't quite plan for such.
Example of specific scenario which will cause issues might be changes in template hierarchy. Let's say you customized `single.php` in version control. Then upstream theme rearranged things and got rid of `single.php` altogether in favor of more generic `singular.php`. Suddenly your changes hang in the air without template to apply them to, essentially your merge is blocked and you have to re-develop your changes on top of a new situation.
With child theme your template will stay in place and continue to work, although occasional updates will be required in some cases as well.
In a nutshell I would consider version control to be essentially a *fork* to maintain, while child theme would be a downstream extension (under your full control) with upstream *dependency*.
In my subjective opinion maintaining a fork would be harder on resources in most cases. I would reserve it to solutions which *cannot* be achieved with a child theme.
|
249,766 |
<p>I have a website that I am updating, it has over 400 posts so updating these manually isn't a very good option. The theme that was used is no longer supported, it has a custom field setup for the featured image. I want to convert that featured image to the WordPress featured image. How can I do this? In the database, the url for the images are stored under wp_postmeta and the meta_key is lifestyle_post_image.</p>
|
[
{
"answer_id": 249767,
"author": "mayersdesign",
"author_id": 106965,
"author_profile": "https://wordpress.stackexchange.com/users/106965",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://wordpress.org/plugins/quick-featured-images/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/quick-featured-images/</a> may very well be what you are looking for. It recently helped me greatly in a similar batch processing situation, and has a bunch of other useful features. Simply saves coding something custom!</p>\n"
},
{
"answer_id": 249781,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>Migrating from one to another isn't that complicated usually. As long as you have the logic you can write code to make it happen and run in bulk or tie it to every time featured image is requested for gradual change over.</p>\n\n<p>The bigger issue I see there is that you say images are stored as <em>URLs</em>. WordPress generally manipulates <em>attachment IDs</em> for this, including featured images. URLs are just too inconvenient to work with for many related purposes.</p>\n\n<p>While going from ID to URL is trivial, going <em>from</em> URL <em>to</em> ID is huge pain in general case. Arbitrary URLs might not even <em>be</em> local attachments. You could see my answer on <a href=\"https://wordpress.stackexchange.com/a/7094/847\">going from URL to ID</a> for a starting point.</p>\n\n<p>Overall without knowing more of your context it is hard to advise on specific approach. If getting to native UI is priority then bulk thorough migration is probably in order. If older posts just need to work sometimes it is easier to just leave them alone with legacy code and move on to new workflow for the current stuff.</p>\n"
},
{
"answer_id": 250022,
"author": "Chris Wathen",
"author_id": 109261,
"author_profile": "https://wordpress.stackexchange.com/users/109261",
"pm_score": 1,
"selected": true,
"text": "<p>I ended up finding another post that helped me achieve what I was trying to do. <a href=\"https://stackoverflow.com/questions/4371929/convert-custom-field-image-to-become-featured-image-in-wordpress\">https://stackoverflow.com/questions/4371929/convert-custom-field-image-to-become-featured-image-in-wordpress</a></p>\n\n<pre><code>$uploads = wp_upload_dir();\n\n// Get all attachment IDs and filenames\n$results = $wpdb->get_results(\"SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file'\");\n\n// Create an 'index' of attachment IDs and their filenames\n$attachments = array();\nforeach ($results as $row)\n$attachments[ intval($row->post_id) ] = $row->meta_value;\n\n// Get all featured images\n$images = $wpdb->get_results(\"SELECT post_id, meta_value AS 'url' FROM $wpdb->postmeta WHERE meta_key = 'lifestyle_post_image'\");\n\n// Loop over each image and try and find attachment post\nforeach ($images as $image) {\nif (preg_match('#^https?://#', $image->url))\n $image->url = str_replace($uploads['baseurl'], '', $image->url); // get relative URL if absolute\n\n$filename = ltrim($image->url, '/');\n\nif ($attachment_ID = array_search($filename, $attachments)) {\n // found attachment, set post thumbnail and delete featured image\n update_post_meta($image->post_id, '_thumbnail_id', $attachment_ID);\n delete_post_meta($image->post_ID, 'Featured Image');\n }\n}\n</code></pre>\n"
}
] |
2016/12/19
|
[
"https://wordpress.stackexchange.com/questions/249766",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109261/"
] |
I have a website that I am updating, it has over 400 posts so updating these manually isn't a very good option. The theme that was used is no longer supported, it has a custom field setup for the featured image. I want to convert that featured image to the WordPress featured image. How can I do this? In the database, the url for the images are stored under wp\_postmeta and the meta\_key is lifestyle\_post\_image.
|
I ended up finding another post that helped me achieve what I was trying to do. <https://stackoverflow.com/questions/4371929/convert-custom-field-image-to-become-featured-image-in-wordpress>
```
$uploads = wp_upload_dir();
// Get all attachment IDs and filenames
$results = $wpdb->get_results("SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file'");
// Create an 'index' of attachment IDs and their filenames
$attachments = array();
foreach ($results as $row)
$attachments[ intval($row->post_id) ] = $row->meta_value;
// Get all featured images
$images = $wpdb->get_results("SELECT post_id, meta_value AS 'url' FROM $wpdb->postmeta WHERE meta_key = 'lifestyle_post_image'");
// Loop over each image and try and find attachment post
foreach ($images as $image) {
if (preg_match('#^https?://#', $image->url))
$image->url = str_replace($uploads['baseurl'], '', $image->url); // get relative URL if absolute
$filename = ltrim($image->url, '/');
if ($attachment_ID = array_search($filename, $attachments)) {
// found attachment, set post thumbnail and delete featured image
update_post_meta($image->post_id, '_thumbnail_id', $attachment_ID);
delete_post_meta($image->post_ID, 'Featured Image');
}
}
```
|
249,797 |
<p>I am trying to retrieve some basic information from the Wordpress database for a theme. However, when the query runs it returns no data. If I run the query on Phpmyadmin, it works fine. Note, wp_places_locator is a table used by a third party plugin.</p>
<pre><code>function get_info($postid) {
global $wpdb;
$info = $wpdb->get_results($wpdb->prepare("SELECT post_id, address, phone, email FROM $wpdb->places_locator WHERE post_id = '$postid'"));
print_r($info);
}
</code></pre>
<p>Thanks!</p>
|
[
{
"answer_id": 249800,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 2,
"selected": true,
"text": "<p>Here you've did something wrong with <code>$wpdb->table_name</code>. It will only return the default WordPress table names. Not custom table names. And also when you call <code>$wpdb->prepare</code> then pass the parameter as array. So your function will be like below- </p>\n\n<pre><code>function get_info($postid) {\n\n global $wpdb;\n // Here I assumed that your table name is '{$wpdb->prefix}places_locator'\n $sql = $wpdb->prepare(\"SELECT post_id, address, phone, email \n FROM {$wpdb->prefix}places_locator \n WHERE post_id = '%d'\", \n array( $postid )\n );\n\n $info = $wpdb->get_results($sql);\n\n return $info;\n\n}\n</code></pre>\n\n<p>Now if you do <code>print_r</code> on <code>get_info()</code> with parameter post ID then it will return you value. </p>\n\n<p>Use like below-</p>\n\n<pre><code>print_r(get_info(1)); // Here I assumed your post ID is 1\n</code></pre>\n"
},
{
"answer_id": 249802,
"author": "Cristiano Baptista",
"author_id": 108188,
"author_profile": "https://wordpress.stackexchange.com/users/108188",
"pm_score": 0,
"selected": false,
"text": "<p>You shouldn't place variables directly on your SQL statement, as <a href=\"https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php\">it is not safe</a></p>\n\n<p>To use <a href=\"https://developer.wordpress.org/reference/classes/wpdb/prepare/\" rel=\"nofollow noreferrer\">WPDB::prepare</a> you need to put unquoted placeholders (like %s for strings or %d for integers) on your SQL and then add the variables in the right order (to match the placeholders) after the first parameter (the SQL statement). </p>\n\n<p>Here are the examples from the WordPress developer reference I linked above:</p>\n\n<pre><code>$wpdb->prepare( \"SELECT * FROM `table` WHERE `column` = %s AND `field` = %d\", 'foo', 1337 );\n$wpdb->prepare( \"SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s\", 'foo' );\n</code></pre>\n\n<p>To fix your code something like this should work:</p>\n\n<pre><code>$info = $wpdb->get_results($wpdb->prepare(\"SELECT post_id, address, phone, email FROM $wpdb->places_locator WHERE post_id = %d\", $postid));\n</code></pre>\n"
}
] |
2016/12/20
|
[
"https://wordpress.stackexchange.com/questions/249797",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106918/"
] |
I am trying to retrieve some basic information from the Wordpress database for a theme. However, when the query runs it returns no data. If I run the query on Phpmyadmin, it works fine. Note, wp\_places\_locator is a table used by a third party plugin.
```
function get_info($postid) {
global $wpdb;
$info = $wpdb->get_results($wpdb->prepare("SELECT post_id, address, phone, email FROM $wpdb->places_locator WHERE post_id = '$postid'"));
print_r($info);
}
```
Thanks!
|
Here you've did something wrong with `$wpdb->table_name`. It will only return the default WordPress table names. Not custom table names. And also when you call `$wpdb->prepare` then pass the parameter as array. So your function will be like below-
```
function get_info($postid) {
global $wpdb;
// Here I assumed that your table name is '{$wpdb->prefix}places_locator'
$sql = $wpdb->prepare("SELECT post_id, address, phone, email
FROM {$wpdb->prefix}places_locator
WHERE post_id = '%d'",
array( $postid )
);
$info = $wpdb->get_results($sql);
return $info;
}
```
Now if you do `print_r` on `get_info()` with parameter post ID then it will return you value.
Use like below-
```
print_r(get_info(1)); // Here I assumed your post ID is 1
```
|
249,815 |
<p>I am running a news website, most of the posts are from an Editor Account. I want to hide the author-box displaying at the bottom of the posts, only for this user. Only author box of Editor should be hidden from public.<br/>
Is there any way to hide the author box of a particular user from public, with a funtion?</p>
<p>Author box element is in loop-single.php file.
wrapped in the footer of the post,</p>
<pre><code><?php echo $td_mod_single->get_social_sharing_bottom();?>
<?php echo $td_mod_single->get_next_prev_posts();?>
<?php echo $td_mod_single->get_author_box();?>
<?php echo $td_mod_single->get_item_scope_meta();?>
</code></pre>
|
[
{
"answer_id": 249818,
"author": "dgarceran",
"author_id": 109222,
"author_profile": "https://wordpress.stackexchange.com/users/109222",
"pm_score": 2,
"selected": true,
"text": "<p>If you know the data of the author, you can wrap that box with an if and the function <a href=\"https://codex.wordpress.org/Function_Reference/get_the_author\" rel=\"nofollow noreferrer\">get_the_author</a></p>\n\n<pre><code>if( get_the_author() == \"name_of_the_author\" ){\n// Don't do it\n}else{\n// Print box\n}\n</code></pre>\n\n<p>EDIT with the final answer updated:</p>\n\n<pre><code><?php echo $td_mod_single->get_social_sharing_bottom();?>\n<?php echo $td_mod_single->get_next_prev_posts();?>\n<?php\n $user = get_user_by(\"login\", \"pknn\"); // user object\n // get_the_author() needs the display name, not the login\n if( get_the_author() != $user->data->display_name ){\n echo $td_mod_single->get_author_box();\n }\n?>\n<?php echo $td_mod_single->get_item_scope_meta();?>\n</code></pre>\n"
},
{
"answer_id": 249820,
"author": "Nicü",
"author_id": 31028,
"author_profile": "https://wordpress.stackexchange.com/users/31028",
"pm_score": 0,
"selected": false,
"text": "<p>It's unclear for me if you want to hide the author box for users with 'editor' role of for the user 'Editor'.</p>\n\n<p>Here's the code for detecting if an user has the editor role and that shows the author box for all other roles:</p>\n\n<pre><code>// Add this in you single post template\n// See https://developer.wordpress.org/themes/basics/template-hierarchy/\n\n// First we get the author role:\nglobal $authordata; // The author object for the current post. See https://codex.wordpress.org/Global_Variables\n$author_roles = $authordata->roles; // Get all author roles. See https://codex.wordpress.org/Class_Reference/WP_User\n$author_role = array_shift( $author_roles ); // Get the user role\n\n// Now we check if the author is an editor\nif ( $author_role != 'editor' ) {\n // Show the author box\n}\n</code></pre>\n\n<p>If you rather want to hide the author box for a specific 'Editor' user, use this instead:</p>\n\n<pre><code>// Add this in you single post template\n// See https://developer.wordpress.org/themes/basics/template-hierarchy/\n\n// First we get the author username:\nglobal $authordata; // The author object for the current post. See https://codex.wordpress.org/Global_Variables\n$username = $authordata->user_login; // Get the author username. See https://codex.wordpress.org/Class_Reference/WP_User\n\n// Now we check if the author username is 'Editor'\nif ( $username != 'Editor' ) {\n // Show the author box\n}\n</code></pre>\n\n<p>Let me know if you find this useful.</p>\n"
}
] |
2016/12/20
|
[
"https://wordpress.stackexchange.com/questions/249815",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109300/"
] |
I am running a news website, most of the posts are from an Editor Account. I want to hide the author-box displaying at the bottom of the posts, only for this user. Only author box of Editor should be hidden from public.
Is there any way to hide the author box of a particular user from public, with a funtion?
Author box element is in loop-single.php file.
wrapped in the footer of the post,
```
<?php echo $td_mod_single->get_social_sharing_bottom();?>
<?php echo $td_mod_single->get_next_prev_posts();?>
<?php echo $td_mod_single->get_author_box();?>
<?php echo $td_mod_single->get_item_scope_meta();?>
```
|
If you know the data of the author, you can wrap that box with an if and the function [get\_the\_author](https://codex.wordpress.org/Function_Reference/get_the_author)
```
if( get_the_author() == "name_of_the_author" ){
// Don't do it
}else{
// Print box
}
```
EDIT with the final answer updated:
```
<?php echo $td_mod_single->get_social_sharing_bottom();?>
<?php echo $td_mod_single->get_next_prev_posts();?>
<?php
$user = get_user_by("login", "pknn"); // user object
// get_the_author() needs the display name, not the login
if( get_the_author() != $user->data->display_name ){
echo $td_mod_single->get_author_box();
}
?>
<?php echo $td_mod_single->get_item_scope_meta();?>
```
|
249,826 |
<p>I have written functionality for checking if custom post title exists or not while adding post. like below:</p>
<pre><code> function wp_exist_post_by_title( $title ) {
global $wpdb;
$return = $wpdb->get_row( "SELECT ID FROM wp_dxwe_posts WHERE post_title = '" . $title . "' && post_status = 'publish' && post_type = 'courses' ", 'ARRAY_N' );
if( empty( $return ) ) {
return false;
} else {
return true;
}
}
</code></pre>
<p>While adding new post my code is below:</p>
<pre><code>$check = $this->wp_exist_post_by_title( $_POST['course_title'] ) ;
if($check==true)
{
$title = '';
echo "<div class='conditional-messages'>Course Already Exists !</div>";
}
else
{
$title=$_POST['course_title'];
}
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => "courses"
);
$description = $_POST['description'];
$id = wp_insert_post($post);
update_post_meta($id, 'course_icon', $attachement_id);
update_post_meta( $id, 'inistitute_name', $institute_name);
</code></pre>
<p>While I am adding new post(course title) it is checking if post_title exists or not perfectly but my problem here is I want to check post title(course title) belongs to only one 'institute_name' because other institutes can have the same course title(custom post) too. I know I need to join 2 tables i.e. 'wp_posts' & 'wp_postmeta', but I was unable to do. can anyone please tell me how to sort out this? Thanks for any help.</p>
|
[
{
"answer_id": 300151,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it like so:</p>\n\n<pre><code>if (get_page_by_title('Some Title', OBJECT, 'post_type')) {\n // Exists\n}\n</code></pre>\n\n<p><strong>post_type</strong> can be \"post\", \"page\", a custom post type slug, etc.</p>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Function_Reference/get_page_by_title\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_page_by_title</a></p>\n"
},
{
"answer_id": 367739,
"author": "Amer Ahmed",
"author_id": 126333,
"author_profile": "https://wordpress.stackexchange.com/users/126333",
"pm_score": 1,
"selected": false,
"text": "<p>Using post_exists() function, you can find out if any of your posts have a certain title.</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/post_exists/\" rel=\"nofollow noreferrer\">Code Reference post_exists()</a></p>\n<p>From comments by "Amirhosseinhpv"</p>\n<blockquote>\n<p>check if post exist by title :</p>\n<pre><code>$found_post = post_exists( "My Post Title",'','','');\necho $found_post ? "Found post at id #$found_post" : "Can't find post!";\n</code></pre>\n<p>Check if custom post type [news] exist by title :</p>\n<pre><code>$found_post = post_exists( "My Post Title",'','','news');\necho $found_post ? "Found post at id #$found_post" : "Can't find post!";\n</code></pre>\n</blockquote>\n<p>You need to include 'wp-admin/includes/post.php' if you performing the check on the frontend as following:</p>\n<p>require_once( ABSPATH . 'wp-admin/includes/post.php' );</p>\n"
}
] |
2016/12/20
|
[
"https://wordpress.stackexchange.com/questions/249826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106542/"
] |
I have written functionality for checking if custom post title exists or not while adding post. like below:
```
function wp_exist_post_by_title( $title ) {
global $wpdb;
$return = $wpdb->get_row( "SELECT ID FROM wp_dxwe_posts WHERE post_title = '" . $title . "' && post_status = 'publish' && post_type = 'courses' ", 'ARRAY_N' );
if( empty( $return ) ) {
return false;
} else {
return true;
}
}
```
While adding new post my code is below:
```
$check = $this->wp_exist_post_by_title( $_POST['course_title'] ) ;
if($check==true)
{
$title = '';
echo "<div class='conditional-messages'>Course Already Exists !</div>";
}
else
{
$title=$_POST['course_title'];
}
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => "courses"
);
$description = $_POST['description'];
$id = wp_insert_post($post);
update_post_meta($id, 'course_icon', $attachement_id);
update_post_meta( $id, 'inistitute_name', $institute_name);
```
While I am adding new post(course title) it is checking if post\_title exists or not perfectly but my problem here is I want to check post title(course title) belongs to only one 'institute\_name' because other institutes can have the same course title(custom post) too. I know I need to join 2 tables i.e. 'wp\_posts' & 'wp\_postmeta', but I was unable to do. can anyone please tell me how to sort out this? Thanks for any help.
|
You can do it like so:
```
if (get_page_by_title('Some Title', OBJECT, 'post_type')) {
// Exists
}
```
**post\_type** can be "post", "page", a custom post type slug, etc.
Reference: <https://codex.wordpress.org/Function_Reference/get_page_by_title>
|
249,827 |
<p>I've been searching for a good few days now trying to get my WordPress event calendar by modern tribe working as I need it to.</p>
<p>I have hundreds of order by and delivery dates in DB each one separated by about 5-10 weeks. what I'm trying to achieve is a list where I can see the all the events starting on today's or yesterday's date.</p>
<p>This sounds simple however the problem appears to be when you query events between two dates it will query both the start and end date giving you historical events which don't need to be seen and can be confusing.</p>
<p>I believe the way to overcome this is with a wp_query and meta_query but no matter which way I try to add the meta query to sort by start date only it breaks the whole thing.</p>
<p>this is the query below any help would be awsome as I've little hair left to pull out!</p>
<pre><code> <?php
$query = new WP_Query( array( 'post_type' => 'tribe_events',
'meta_query' => array(
array(
'key' => '_EventStartDate',
'value' => date('Y-m-d H:i:s', strtotime('-1 week')),
'compare' => 'date'
)
)
) );
if ($query->have_posts())
{
while ($query->have_posts()) : $query->the_post();
echo $query->post->EventStartDate . ' ';
echo $query->post->post_title . '</br>';
endwhile;
}
wp_reset_query();
?>
</code></pre>
<p>I've also tried changing the meta value to</p>
<pre><code> 'value' => date('Y-m-d', strtotime('-1 week')),
</code></pre>
<p>but this didnt work either...</p>
<p>Thanks</p>
|
[
{
"answer_id": 300151,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it like so:</p>\n\n<pre><code>if (get_page_by_title('Some Title', OBJECT, 'post_type')) {\n // Exists\n}\n</code></pre>\n\n<p><strong>post_type</strong> can be \"post\", \"page\", a custom post type slug, etc.</p>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Function_Reference/get_page_by_title\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_page_by_title</a></p>\n"
},
{
"answer_id": 367739,
"author": "Amer Ahmed",
"author_id": 126333,
"author_profile": "https://wordpress.stackexchange.com/users/126333",
"pm_score": 1,
"selected": false,
"text": "<p>Using post_exists() function, you can find out if any of your posts have a certain title.</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/post_exists/\" rel=\"nofollow noreferrer\">Code Reference post_exists()</a></p>\n<p>From comments by "Amirhosseinhpv"</p>\n<blockquote>\n<p>check if post exist by title :</p>\n<pre><code>$found_post = post_exists( "My Post Title",'','','');\necho $found_post ? "Found post at id #$found_post" : "Can't find post!";\n</code></pre>\n<p>Check if custom post type [news] exist by title :</p>\n<pre><code>$found_post = post_exists( "My Post Title",'','','news');\necho $found_post ? "Found post at id #$found_post" : "Can't find post!";\n</code></pre>\n</blockquote>\n<p>You need to include 'wp-admin/includes/post.php' if you performing the check on the frontend as following:</p>\n<p>require_once( ABSPATH . 'wp-admin/includes/post.php' );</p>\n"
}
] |
2016/12/20
|
[
"https://wordpress.stackexchange.com/questions/249827",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91255/"
] |
I've been searching for a good few days now trying to get my WordPress event calendar by modern tribe working as I need it to.
I have hundreds of order by and delivery dates in DB each one separated by about 5-10 weeks. what I'm trying to achieve is a list where I can see the all the events starting on today's or yesterday's date.
This sounds simple however the problem appears to be when you query events between two dates it will query both the start and end date giving you historical events which don't need to be seen and can be confusing.
I believe the way to overcome this is with a wp\_query and meta\_query but no matter which way I try to add the meta query to sort by start date only it breaks the whole thing.
this is the query below any help would be awsome as I've little hair left to pull out!
```
<?php
$query = new WP_Query( array( 'post_type' => 'tribe_events',
'meta_query' => array(
array(
'key' => '_EventStartDate',
'value' => date('Y-m-d H:i:s', strtotime('-1 week')),
'compare' => 'date'
)
)
) );
if ($query->have_posts())
{
while ($query->have_posts()) : $query->the_post();
echo $query->post->EventStartDate . ' ';
echo $query->post->post_title . '</br>';
endwhile;
}
wp_reset_query();
?>
```
I've also tried changing the meta value to
```
'value' => date('Y-m-d', strtotime('-1 week')),
```
but this didnt work either...
Thanks
|
You can do it like so:
```
if (get_page_by_title('Some Title', OBJECT, 'post_type')) {
// Exists
}
```
**post\_type** can be "post", "page", a custom post type slug, etc.
Reference: <https://codex.wordpress.org/Function_Reference/get_page_by_title>
|
249,854 |
<p>I am trying to replace the image at <a href="https://imgur.com/a/IHwaC" rel="nofollow noreferrer">http://imgur.com/a/IHwaC</a> (wont let me upload it to here for some reason) with another image but whenever I do it it just seems to make the background white and not actually do anything.
The way I change them is by uploading the image to the WordPress media library and replacing the image name with the other image name.</p>
<p><strong>My Questions:</strong></p>
<p>Am I doing something wrong when trying to upload?</p>
<p>Is my image sized wrong?</p>
<p>(I'm running WordPress on academyofperformancearts.com.)</p>
|
[
{
"answer_id": 300151,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it like so:</p>\n\n<pre><code>if (get_page_by_title('Some Title', OBJECT, 'post_type')) {\n // Exists\n}\n</code></pre>\n\n<p><strong>post_type</strong> can be \"post\", \"page\", a custom post type slug, etc.</p>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Function_Reference/get_page_by_title\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_page_by_title</a></p>\n"
},
{
"answer_id": 367739,
"author": "Amer Ahmed",
"author_id": 126333,
"author_profile": "https://wordpress.stackexchange.com/users/126333",
"pm_score": 1,
"selected": false,
"text": "<p>Using post_exists() function, you can find out if any of your posts have a certain title.</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/post_exists/\" rel=\"nofollow noreferrer\">Code Reference post_exists()</a></p>\n<p>From comments by "Amirhosseinhpv"</p>\n<blockquote>\n<p>check if post exist by title :</p>\n<pre><code>$found_post = post_exists( "My Post Title",'','','');\necho $found_post ? "Found post at id #$found_post" : "Can't find post!";\n</code></pre>\n<p>Check if custom post type [news] exist by title :</p>\n<pre><code>$found_post = post_exists( "My Post Title",'','','news');\necho $found_post ? "Found post at id #$found_post" : "Can't find post!";\n</code></pre>\n</blockquote>\n<p>You need to include 'wp-admin/includes/post.php' if you performing the check on the frontend as following:</p>\n<p>require_once( ABSPATH . 'wp-admin/includes/post.php' );</p>\n"
}
] |
2016/12/20
|
[
"https://wordpress.stackexchange.com/questions/249854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109320/"
] |
I am trying to replace the image at [http://imgur.com/a/IHwaC](https://imgur.com/a/IHwaC) (wont let me upload it to here for some reason) with another image but whenever I do it it just seems to make the background white and not actually do anything.
The way I change them is by uploading the image to the WordPress media library and replacing the image name with the other image name.
**My Questions:**
Am I doing something wrong when trying to upload?
Is my image sized wrong?
(I'm running WordPress on academyofperformancearts.com.)
|
You can do it like so:
```
if (get_page_by_title('Some Title', OBJECT, 'post_type')) {
// Exists
}
```
**post\_type** can be "post", "page", a custom post type slug, etc.
Reference: <https://codex.wordpress.org/Function_Reference/get_page_by_title>
|
249,881 |
<p>I am trying to order blog posts by 'city' first and then order by 'street_name' within each city. I can't seem to get the 'street_name' to display in alphabetical order. I am using WP_Query:</p>
<pre><code> <?php
$args = array(
'post_type'=> 'property',
'meta_query' => array(
array(
'relation' => 'AND' ,
array(
'meta_key' => 'city',
'orderby' => 'meta_value',
'order' => 'ASC'
),
array(
'meta_key' => 'street_name',
'orderby' => 'meta_value',
'order' => 'ASC'
),
)
</code></pre>
<p>),
Any ideas?</p>
|
[
{
"answer_id": 249894,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 3,
"selected": false,
"text": "<p><code>meta_query</code> and <code>orderby</code> are seperate parameters, you just put them together in an array. You will have to do one then the other.</p>\n\n<p>e.g.</p>\n\n<pre><code><?php\n$args = array(\n 'post_type' => 'property',\n 'meta_query' => array(\n array(\n 'relation' => 'AND',\n 'city_clause' => array(\n 'key' => 'city',\n 'compare' => 'EXISTS',\n ),\n 'street_clause' => array(\n 'key' => 'street_name',\n 'compare' => 'EXISTS',\n ),\n )\n )\n 'orderby' => array(\n 'city_clause' => 'desc',\n 'street_clause' => 'desc',\n )\n)\n?>\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"noreferrer\">https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters</a></p>\n"
},
{
"answer_id": 249989,
"author": "Michael H",
"author_id": 107176,
"author_profile": "https://wordpress.stackexchange.com/users/107176",
"pm_score": 1,
"selected": false,
"text": "<p>You need to order by specific clauses for meta_query.</p>\n\n<p>This link should cover everything to help you sort out the syntax and get it working.</p>\n\n<p><a href=\"https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/</a></p>\n"
},
{
"answer_id": 305050,
"author": "aayushdrolia",
"author_id": 144653,
"author_profile": "https://wordpress.stackexchange.com/users/144653",
"pm_score": -1,
"selected": false,
"text": "<p>Try this, it might help.</p>\n\n<pre><code><?php\n$args = array(\n'post_type' => 'Sports',\n'meta_query' => array(\n array(\n 'key' => 'league_count',\n 'orderby' => 'meta_value_num', /* use this only \n if the key stores number otherwise use 'meta_value' */\n 'order' => 'ASC'\n ),\n array(\n 'key' => 'matches_count',\n 'orderby' => 'meta_value_num',\n 'order' => 'ASC'\n ),\n),\n);\n$query = new WP_Query( $args );\n?>\n</code></pre>\n"
},
{
"answer_id": 363181,
"author": "Keith Gardner",
"author_id": 131071,
"author_profile": "https://wordpress.stackexchange.com/users/131071",
"pm_score": 2,
"selected": false,
"text": "<p>Took me awhile to figure out how to order by numeric values with multiple meta keys since you can't just use orderby meta_value_num. Instead you set the type to numeric in the meta query. This is working production code.</p>\n\n<pre><code> $meta_query = array(\n 'relation' => 'AND',\n 'query_one' => array(\n 'key' => '_rama_ads_type'\n ),\n 'query_two' => array(\n 'key' => '_rama_ads_order',\n 'type' => 'NUMERIC',\n ),\n );\n\n $order_by = array(\n 'query_one' => 'ASC',\n 'query_two' => 'DESC',\n );\n\n $query->set( 'meta_query', $meta_query );\n $query->set( 'orderby', $order_by );\n</code></pre>\n"
}
] |
2016/12/20
|
[
"https://wordpress.stackexchange.com/questions/249881",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109345/"
] |
I am trying to order blog posts by 'city' first and then order by 'street\_name' within each city. I can't seem to get the 'street\_name' to display in alphabetical order. I am using WP\_Query:
```
<?php
$args = array(
'post_type'=> 'property',
'meta_query' => array(
array(
'relation' => 'AND' ,
array(
'meta_key' => 'city',
'orderby' => 'meta_value',
'order' => 'ASC'
),
array(
'meta_key' => 'street_name',
'orderby' => 'meta_value',
'order' => 'ASC'
),
)
```
),
Any ideas?
|
`meta_query` and `orderby` are seperate parameters, you just put them together in an array. You will have to do one then the other.
e.g.
```
<?php
$args = array(
'post_type' => 'property',
'meta_query' => array(
array(
'relation' => 'AND',
'city_clause' => array(
'key' => 'city',
'compare' => 'EXISTS',
),
'street_clause' => array(
'key' => 'street_name',
'compare' => 'EXISTS',
),
)
)
'orderby' => array(
'city_clause' => 'desc',
'street_clause' => 'desc',
)
)
?>
```
<https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters>
|
249,900 |
<p>I'm having issues with a query. I want to get the images attached to an individual post of the type <em>rental</em>.</p>
<p>My query is broken as it outputs all the images on the entire site:</p>
<pre><code>$image_query = new WP_Query(
array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'post_parent' => $rental->post->ID,
'order' => 'DESC'
)
);
if( $image_query->have_posts() ){
while( $image_query->have_posts() ) {
$image_query->the_post();
$imgurl = wp_get_attachment_url( get_the_ID() );
echo '<div class="item">';
echo '<img src="'.$imgurl.'">';
echo '</div>';
}
wp_reset_postdata();
}
</code></pre>
<p>Any ideas on how I can adjust this to only get the images attached to the current post?</p>
|
[
{
"answer_id": 249894,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 3,
"selected": false,
"text": "<p><code>meta_query</code> and <code>orderby</code> are seperate parameters, you just put them together in an array. You will have to do one then the other.</p>\n\n<p>e.g.</p>\n\n<pre><code><?php\n$args = array(\n 'post_type' => 'property',\n 'meta_query' => array(\n array(\n 'relation' => 'AND',\n 'city_clause' => array(\n 'key' => 'city',\n 'compare' => 'EXISTS',\n ),\n 'street_clause' => array(\n 'key' => 'street_name',\n 'compare' => 'EXISTS',\n ),\n )\n )\n 'orderby' => array(\n 'city_clause' => 'desc',\n 'street_clause' => 'desc',\n )\n)\n?>\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"noreferrer\">https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters</a></p>\n"
},
{
"answer_id": 249989,
"author": "Michael H",
"author_id": 107176,
"author_profile": "https://wordpress.stackexchange.com/users/107176",
"pm_score": 1,
"selected": false,
"text": "<p>You need to order by specific clauses for meta_query.</p>\n\n<p>This link should cover everything to help you sort out the syntax and get it working.</p>\n\n<p><a href=\"https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/</a></p>\n"
},
{
"answer_id": 305050,
"author": "aayushdrolia",
"author_id": 144653,
"author_profile": "https://wordpress.stackexchange.com/users/144653",
"pm_score": -1,
"selected": false,
"text": "<p>Try this, it might help.</p>\n\n<pre><code><?php\n$args = array(\n'post_type' => 'Sports',\n'meta_query' => array(\n array(\n 'key' => 'league_count',\n 'orderby' => 'meta_value_num', /* use this only \n if the key stores number otherwise use 'meta_value' */\n 'order' => 'ASC'\n ),\n array(\n 'key' => 'matches_count',\n 'orderby' => 'meta_value_num',\n 'order' => 'ASC'\n ),\n),\n);\n$query = new WP_Query( $args );\n?>\n</code></pre>\n"
},
{
"answer_id": 363181,
"author": "Keith Gardner",
"author_id": 131071,
"author_profile": "https://wordpress.stackexchange.com/users/131071",
"pm_score": 2,
"selected": false,
"text": "<p>Took me awhile to figure out how to order by numeric values with multiple meta keys since you can't just use orderby meta_value_num. Instead you set the type to numeric in the meta query. This is working production code.</p>\n\n<pre><code> $meta_query = array(\n 'relation' => 'AND',\n 'query_one' => array(\n 'key' => '_rama_ads_type'\n ),\n 'query_two' => array(\n 'key' => '_rama_ads_order',\n 'type' => 'NUMERIC',\n ),\n );\n\n $order_by = array(\n 'query_one' => 'ASC',\n 'query_two' => 'DESC',\n );\n\n $query->set( 'meta_query', $meta_query );\n $query->set( 'orderby', $order_by );\n</code></pre>\n"
}
] |
2016/12/21
|
[
"https://wordpress.stackexchange.com/questions/249900",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109355/"
] |
I'm having issues with a query. I want to get the images attached to an individual post of the type *rental*.
My query is broken as it outputs all the images on the entire site:
```
$image_query = new WP_Query(
array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'post_parent' => $rental->post->ID,
'order' => 'DESC'
)
);
if( $image_query->have_posts() ){
while( $image_query->have_posts() ) {
$image_query->the_post();
$imgurl = wp_get_attachment_url( get_the_ID() );
echo '<div class="item">';
echo '<img src="'.$imgurl.'">';
echo '</div>';
}
wp_reset_postdata();
}
```
Any ideas on how I can adjust this to only get the images attached to the current post?
|
`meta_query` and `orderby` are seperate parameters, you just put them together in an array. You will have to do one then the other.
e.g.
```
<?php
$args = array(
'post_type' => 'property',
'meta_query' => array(
array(
'relation' => 'AND',
'city_clause' => array(
'key' => 'city',
'compare' => 'EXISTS',
),
'street_clause' => array(
'key' => 'street_name',
'compare' => 'EXISTS',
),
)
)
'orderby' => array(
'city_clause' => 'desc',
'street_clause' => 'desc',
)
)
?>
```
<https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters>
|
249,901 |
<p>I want to break the loop into sections of posts so I can put content in between that doesn't repeat. Is it possible to end the loop and restart?</p>
<p>My code works for my layout works if there are 10 posts on a page. When I have fewer it breaks because the closing div for .grid is tied in with the 10th post showing. </p>
<p>This shows my layout: 1st post, 2-5 in a grid, a non-post div separating, repeat of post then posts in a grid.
<a href="https://i.stack.imgur.com/LkGmi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LkGmi.png" alt="layout"></a></p>
<pre><code> <?php if ( have_posts() ) :
$count = 0;
while ( have_posts() ) : the_post();
$count++;
if ($count == 1) : ?>
<article class="large"></article>
<?php elseif ($count == 2) : ?>
<div class="grid">
<article></article>
<?php elseif ($count == 3) : ?>
<article></article>
<?php elseif ($count == 4) : ?>
<article></article>
<?php elseif ($count == 5) : ?>
<article></article>
</div> <!-- .grid -->
<div id="edit">
</div> <!-- #edit -->
<?php elseif ($count == 6) : ?>
<article class="large"></article>
<?php elseif ($count == 7) : ?>
<div class="grid">
<article></article>
<?php elseif ($count == 8) : ?>
<article></article>
<?php elseif ($count == 9) : ?>
<article></article>
<?php elseif ($count == 10) : ?>
<article></article>
</div> <!-- .grid -->
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
</code></pre>
|
[
{
"answer_id": 249906,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": -1,
"selected": false,
"text": "<p>You can use before the <code>while</code> loop</p>\n\n<pre><code>global $wp_query;\n$total_posts = $wp_query->post_count;\n</code></pre>\n\n<p>To get the number of the posts you will get since not always you will get 10.</p>\n\n<p>Now, <code>$total_posts</code> can help you create the custom logic you need.</p>\n"
},
{
"answer_id": 249907,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 0,
"selected": false,
"text": "<p>This pattern can be reduced to two main sections, large box and grid boxes.</p>\n\n<p>And you said you were having trouble closing the grid boxes when your posts are less than 10, an easy way to close off the grid would be to check if the current post is equal to the total posts.</p>\n\n<p>Here is my interpretation of your loop:</p>\n\n<pre><code><?php\nif (have_posts()) :\n while (have_posts()) :\n the_post();\n $total_posts = $wp_query->post_count;\n $current_post = $wp_query->current_post;\n\n // Large boxes\n if (in_array($current_post, array(1, 6))) : ?>\n\n <article class=\"large\"></article>\n <?php\n elseif ($current_post > 1 && $current_post < 6 || $current_post > 6) :\n // Open grid box\n in_array($current_post, array(2, 7)) ? \"<div class='grid'>\" : \"\";\n ?>\n <article></article>\n <?php\n // Close grid box\n in_array($current_post, array(6, $total_posts)) ? \"</div> <!-- .grid -->\" : \"\";\n // Add seperator\n $current_post == 6 ? \"<div id='edit'></div> <!-- #edit -->\" : \"\";\n\n endif;\n\n endwhile;\nendif;\n?>\n</code></pre>\n"
}
] |
2016/12/21
|
[
"https://wordpress.stackexchange.com/questions/249901",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78026/"
] |
I want to break the loop into sections of posts so I can put content in between that doesn't repeat. Is it possible to end the loop and restart?
My code works for my layout works if there are 10 posts on a page. When I have fewer it breaks because the closing div for .grid is tied in with the 10th post showing.
This shows my layout: 1st post, 2-5 in a grid, a non-post div separating, repeat of post then posts in a grid.
[](https://i.stack.imgur.com/LkGmi.png)
```
<?php if ( have_posts() ) :
$count = 0;
while ( have_posts() ) : the_post();
$count++;
if ($count == 1) : ?>
<article class="large"></article>
<?php elseif ($count == 2) : ?>
<div class="grid">
<article></article>
<?php elseif ($count == 3) : ?>
<article></article>
<?php elseif ($count == 4) : ?>
<article></article>
<?php elseif ($count == 5) : ?>
<article></article>
</div> <!-- .grid -->
<div id="edit">
</div> <!-- #edit -->
<?php elseif ($count == 6) : ?>
<article class="large"></article>
<?php elseif ($count == 7) : ?>
<div class="grid">
<article></article>
<?php elseif ($count == 8) : ?>
<article></article>
<?php elseif ($count == 9) : ?>
<article></article>
<?php elseif ($count == 10) : ?>
<article></article>
</div> <!-- .grid -->
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
```
|
This pattern can be reduced to two main sections, large box and grid boxes.
And you said you were having trouble closing the grid boxes when your posts are less than 10, an easy way to close off the grid would be to check if the current post is equal to the total posts.
Here is my interpretation of your loop:
```
<?php
if (have_posts()) :
while (have_posts()) :
the_post();
$total_posts = $wp_query->post_count;
$current_post = $wp_query->current_post;
// Large boxes
if (in_array($current_post, array(1, 6))) : ?>
<article class="large"></article>
<?php
elseif ($current_post > 1 && $current_post < 6 || $current_post > 6) :
// Open grid box
in_array($current_post, array(2, 7)) ? "<div class='grid'>" : "";
?>
<article></article>
<?php
// Close grid box
in_array($current_post, array(6, $total_posts)) ? "</div> <!-- .grid -->" : "";
// Add seperator
$current_post == 6 ? "<div id='edit'></div> <!-- #edit -->" : "";
endif;
endwhile;
endif;
?>
```
|
249,918 |
<p>I am using wordpress 4.6.</p>
<p>I have template register form with page URL <code>domain-name/account/?action=register</code></p>
<p>I want to redirect it to home page after register but instead of that it show </p>
<p>message "You have logged in. You better go to Home" with page URL </p>
<pre><code>domain-name/account/?result=registered.
</code></pre>
<p>I already try below code in theme functions.php</p>
<pre><code>function __my_registration_redirect(){
wp_redirect( '/my-account' );
exit;
}
add_filter( 'registration_redirect', '__my_registration_redirect' );
</code></pre>
<p>but nothing happens</p>
|
[
{
"answer_id": 249923,
"author": "Ranuka",
"author_id": 106350,
"author_profile": "https://wordpress.stackexchange.com/users/106350",
"pm_score": 2,
"selected": false,
"text": "<p>Instead of your code why don't you try which in the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/registration_redirect\" rel=\"nofollow noreferrer\">codex example</a>. </p>\n\n<p>This simple example will redirect a user to the <code>home_url()</code> upon successful registration.</p>\n\n<pre><code>add_filter( 'registration_redirect', 'my_redirect_home' );\nfunction my_redirect_home( $registration_redirect ) {\n return home_url();\n}\n</code></pre>\n"
},
{
"answer_id": 253965,
"author": "RobBenz",
"author_id": 85437,
"author_profile": "https://wordpress.stackexchange.com/users/85437",
"pm_score": 0,
"selected": false,
"text": "<p>you can try this code below for log in and log out redirects </p>\n\n<pre><code>// -- LOGIN | LOGOUT STUFF -- functions.php\n//add_filter('user_register', 'login_redirect'); \nadd_filter('wp_login', 'login_redirect');\nfunction login_redirect($redirect_to) {\n wp_redirect( home_url() );\n exit();\n}\n\nadd_action('wp_logout','logout_redirect');\nfunction logout_redirect(){\n wp_redirect( home_url() );\n exit();\n}\n/* END */\n</code></pre>\n"
}
] |
2016/12/21
|
[
"https://wordpress.stackexchange.com/questions/249918",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109080/"
] |
I am using wordpress 4.6.
I have template register form with page URL `domain-name/account/?action=register`
I want to redirect it to home page after register but instead of that it show
message "You have logged in. You better go to Home" with page URL
```
domain-name/account/?result=registered.
```
I already try below code in theme functions.php
```
function __my_registration_redirect(){
wp_redirect( '/my-account' );
exit;
}
add_filter( 'registration_redirect', '__my_registration_redirect' );
```
but nothing happens
|
Instead of your code why don't you try which in the [codex example](https://codex.wordpress.org/Plugin_API/Filter_Reference/registration_redirect).
This simple example will redirect a user to the `home_url()` upon successful registration.
```
add_filter( 'registration_redirect', 'my_redirect_home' );
function my_redirect_home( $registration_redirect ) {
return home_url();
}
```
|
249,929 |
<p>please give me advice Im very new to ajax, I have a list of posts, if I click it will display the posts information in a div without load the page. I know I must use ajax, so I create a file: loadcontent.php in a root folder and use this code below, but I don't know how to send and get data throught ajax. I need to pass an id in order to get post infos.</p>
<pre><code><script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_id = $(this).attr("rel"); //this is the post id
$("#post-container").html("content loading");
$("#post-container").load("/loadcontent.php");
return false;
});
});
</script>
</code></pre>
|
[
{
"answer_id": 249932,
"author": "Kaeles",
"author_id": 109375,
"author_profile": "https://wordpress.stackexchange.com/users/109375",
"pm_score": 4,
"selected": true,
"text": "<p>Use Ajax API provided by WordPress.</p>\n\n<p>In first time, fix your Ajax request :</p>\n\n<pre><code><script>\n$(\".post-link\").click(function(){\n var post_id = $(this).attr(\"rel\"); //this is the post id\n $(\"#post-container\").html(\"content loading\");\n $.ajax({\n url: myapiurl.ajax_url,\n type: 'post|get|put',\n data: {\n action: 'my_php_function_name',\n post_id: post_id\n },\n success: function(data) {\n // What I have to do...\n },\n fail: {\n // What I have to do...\n }\n });\n return false;\n});\n</script> \n</code></pre>\n\n<p>Now, you have to create your WordPress treatment. You can put this code in your functions.php or in a plugin file.</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'my_ajax_scripts' );\nfunction my_ajax_scripts() {\n wp_localize_script( 'ajaxRequestId', 'myapiurl', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );\n}\n</code></pre>\n\n<p>And then... your function that retrieve your posts</p>\n\n<pre><code>function my_php_function_name() {\n // What I have to do...\n}\n</code></pre>\n\n<p>PS: Never put code in root install folder. Use functions.php of your theme, or create plugin. It's very important for maintainability and security. Have fun :)</p>\n"
},
{
"answer_id": 404799,
"author": "samjco",
"author_id": 29133,
"author_profile": "https://wordpress.stackexchange.com/users/29133",
"pm_score": 0,
"selected": false,
"text": "<p>The html</p>\n<pre><code><button class="the-btn">click me</button>\n<div class="container"></div>\n</code></pre>\n<p>The js:</p>\n<pre><code><script>\njQuery(".the-btn").click(function(){\n\n var param1 = 'something';\n var param2 = 'something else';\n\n $("div.container").html("content loading....");\n\n jQuery.ajax({\n url: ajaxurl,\n type: POST, //'post|get|put'\n data: {\n action: 'my_php_function_name', 'param1':'something', 'param2':'something else'\n \n },\n success: function(data) {\n // What I have to do...\n jQuery("div.container").html(data);\n\n },\n fail: {\n // What I have to do...\n jQuery("div.container").html("data failed to load");\n }\n })\n return false;\n});\n</script>\n</code></pre>\n<p>Add to functions.php</p>\n<pre><code>//So, if you want it to fire on the front-end for both visitors and logged-in users, you can do this:\n\nadd_action('wp_ajax_load_my_php_function_name', 'my_php_function_name'); \nadd_action('wp_ajax_nopriv_my_php_function_name', 'my_php_function_name'); \n\nfunction my_php_function_name() {\n\n $param1 = $_POST['param1'];\n $param2 = $_POST['param2'];\n\n echo $param1." ".$param2;\n\n}\n</code></pre>\n<p>If ajaxurl is not defined, which it should be, but if it'a not, add this:</p>\n<pre><code><script type="text/javascript">\nvar ajaxurl = '<?php echo str_replace( array('http:', 'https:'), '', admin_url('admin-ajax.php') ); ?>';\n</script>\n</code></pre>\n<p>More information on ajax and Wordpress:\n<a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/AJAX_in_Plugins</a></p>\n"
}
] |
2016/12/21
|
[
"https://wordpress.stackexchange.com/questions/249929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103681/"
] |
please give me advice Im very new to ajax, I have a list of posts, if I click it will display the posts information in a div without load the page. I know I must use ajax, so I create a file: loadcontent.php in a root folder and use this code below, but I don't know how to send and get data throught ajax. I need to pass an id in order to get post infos.
```
<script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_id = $(this).attr("rel"); //this is the post id
$("#post-container").html("content loading");
$("#post-container").load("/loadcontent.php");
return false;
});
});
</script>
```
|
Use Ajax API provided by WordPress.
In first time, fix your Ajax request :
```
<script>
$(".post-link").click(function(){
var post_id = $(this).attr("rel"); //this is the post id
$("#post-container").html("content loading");
$.ajax({
url: myapiurl.ajax_url,
type: 'post|get|put',
data: {
action: 'my_php_function_name',
post_id: post_id
},
success: function(data) {
// What I have to do...
},
fail: {
// What I have to do...
}
});
return false;
});
</script>
```
Now, you have to create your WordPress treatment. You can put this code in your functions.php or in a plugin file.
```
add_action( 'admin_enqueue_scripts', 'my_ajax_scripts' );
function my_ajax_scripts() {
wp_localize_script( 'ajaxRequestId', 'myapiurl', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
```
And then... your function that retrieve your posts
```
function my_php_function_name() {
// What I have to do...
}
```
PS: Never put code in root install folder. Use functions.php of your theme, or create plugin. It's very important for maintainability and security. Have fun :)
|
249,931 |
<p>I want to include a file only in single post page. I've following code but not working;</p>
<pre><code>if (is_single()){
require_once(dirname(__FILE__) . '/inc/lazy-load.php');
}
</code></pre>
<p>I mean i just want to load lazy-load in only single post page. but above code is not working. Any idea? Hope to get a solve for this problem.</p>
|
[
{
"answer_id": 249941,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>The best way would be to create a child theme then duplicate your <code>single.php</code> template file and edit that directly.</p>\n<blockquote>\n<p><strong><a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">CHILD THEMES</a></strong></p>\n<p>A child theme is a theme that inherits the functionality and styling\nof another theme, called the parent theme. Child themes are the\nrecommended way of modifying an existing theme.</p>\n</blockquote>\n"
},
{
"answer_id": 249942,
"author": "Omar Elsayed",
"author_id": 109382,
"author_profile": "https://wordpress.stackexchange.com/users/109382",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/is_single/\" rel=\"nofollow noreferrer\">is_single</a> function checks for $wp_query global variable is loading single post of any post type or not , $wp_query is set after running query_posts function that loaded after <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp\" rel=\"nofollow noreferrer\">wp</a> action hook.</p>\n\n<p>So you should call this function in the right order ( hook )</p>\n\n<pre><code>add_action( 'wp', 'include_single_lazy_load' );\n\nfunction include_single_lazy_load() {\n if( is_single() ) {\n require_once(dirname(__FILE__) . '/inc/lazy-load.php');\n }\n}\n</code></pre>\n"
}
] |
2016/12/21
|
[
"https://wordpress.stackexchange.com/questions/249931",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109374/"
] |
I want to include a file only in single post page. I've following code but not working;
```
if (is_single()){
require_once(dirname(__FILE__) . '/inc/lazy-load.php');
}
```
I mean i just want to load lazy-load in only single post page. but above code is not working. Any idea? Hope to get a solve for this problem.
|
[is\_single](https://developer.wordpress.org/reference/functions/is_single/) function checks for $wp\_query global variable is loading single post of any post type or not , $wp\_query is set after running query\_posts function that loaded after [wp](https://codex.wordpress.org/Plugin_API/Action_Reference/wp) action hook.
So you should call this function in the right order ( hook )
```
add_action( 'wp', 'include_single_lazy_load' );
function include_single_lazy_load() {
if( is_single() ) {
require_once(dirname(__FILE__) . '/inc/lazy-load.php');
}
}
```
|
249,933 |
<p>I recently stumbled upon this and was wondering if calling <code>wp_mail()</code> in a theme is allowed or not as per WordPress standards. I should clarify that I'm not overriding it as a pluggable function in the theme, I am just calling it if it exists.</p>
<p>I'm asking here because I've been searching for this but did not find any clear answer stating anything like this.</p>
|
[
{
"answer_id": 249941,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>The best way would be to create a child theme then duplicate your <code>single.php</code> template file and edit that directly.</p>\n<blockquote>\n<p><strong><a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">CHILD THEMES</a></strong></p>\n<p>A child theme is a theme that inherits the functionality and styling\nof another theme, called the parent theme. Child themes are the\nrecommended way of modifying an existing theme.</p>\n</blockquote>\n"
},
{
"answer_id": 249942,
"author": "Omar Elsayed",
"author_id": 109382,
"author_profile": "https://wordpress.stackexchange.com/users/109382",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/is_single/\" rel=\"nofollow noreferrer\">is_single</a> function checks for $wp_query global variable is loading single post of any post type or not , $wp_query is set after running query_posts function that loaded after <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp\" rel=\"nofollow noreferrer\">wp</a> action hook.</p>\n\n<p>So you should call this function in the right order ( hook )</p>\n\n<pre><code>add_action( 'wp', 'include_single_lazy_load' );\n\nfunction include_single_lazy_load() {\n if( is_single() ) {\n require_once(dirname(__FILE__) . '/inc/lazy-load.php');\n }\n}\n</code></pre>\n"
}
] |
2016/12/21
|
[
"https://wordpress.stackexchange.com/questions/249933",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97347/"
] |
I recently stumbled upon this and was wondering if calling `wp_mail()` in a theme is allowed or not as per WordPress standards. I should clarify that I'm not overriding it as a pluggable function in the theme, I am just calling it if it exists.
I'm asking here because I've been searching for this but did not find any clear answer stating anything like this.
|
[is\_single](https://developer.wordpress.org/reference/functions/is_single/) function checks for $wp\_query global variable is loading single post of any post type or not , $wp\_query is set after running query\_posts function that loaded after [wp](https://codex.wordpress.org/Plugin_API/Action_Reference/wp) action hook.
So you should call this function in the right order ( hook )
```
add_action( 'wp', 'include_single_lazy_load' );
function include_single_lazy_load() {
if( is_single() ) {
require_once(dirname(__FILE__) . '/inc/lazy-load.php');
}
}
```
|
249,948 |
<p>My post template won't load the stylesheet, what's going wrong?</p>
<pre><code>function wpse_enqueue_post_template_styles() {
if ( is_post_template( 'category-bedrijven.php' ) ) {
wp_enqueue_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );
</code></pre>
|
[
{
"answer_id": 249951,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>You can do it like-</p>\n\n<pre><code>function wpse_enqueue_post_template_styles() {\n if ( is_category('bedrijven') ) {\n wp_enqueue_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );\n</code></pre>\n\n<p>Here <strong><em>bedrijven</em></strong> is your category slug.</p>\n\n<p>As you said the above method hasn't worked for you, so here I'm suggesting another method-</p>\n\n<p>First remove the first method's full code. Then follow this below method step by step-</p>\n\n<p><strong>Step 1:</strong> \nIn your theme's <code>functions.php</code> put the below code block-</p>\n\n<pre><code>function the_dramatist_register_category_styles() {\n wp_register_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'the_dramatist_register_category_styles' );\n</code></pre>\n\n<p>By this above code block we are registering your stylesheet file at <strong><em>WordPress</em></strong>. So we can call it anytime.</p>\n\n<p><strong>Step 2:</strong>\nNow go to your <code>category-bedrijven.php</code> file and inside this file put the below code-</p>\n\n<pre><code><?php wp_enqueue_style('post-template'); ?>\n</code></pre>\n\n<p>It'll must work if you do it right. </p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 249952,
"author": "Mohamed Rihan",
"author_id": 85768,
"author_profile": "https://wordpress.stackexchange.com/users/85768",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function wpse_enqueue_post_template_styles() {\n\n if ( is_page_template( 'category-bedrijven.php' ) ) {\n wp_enqueue_style( 'cat-style', get_stylesheet_directory_uri() . '/layout-interieur.css' ); \n } \n}\n add_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );\n</code></pre>\n"
},
{
"answer_id": 249980,
"author": "Khuram",
"author_id": 109088,
"author_profile": "https://wordpress.stackexchange.com/users/109088",
"pm_score": 0,
"selected": false,
"text": "<p>You can do like this:</p>\n\n<p>$handle = 'wpdocs';</p>\n\n<p>wp_register_style( $handle, </p>\n\n<p>get_stylesheet_directory_uri().'/relative/path/to/stylesheet.css', array(), '', true );</p>\n\n<p>if ( is_page_template( 'template-name.php' ) ) {\n wp_enqueue_style( $handle );\n}</p>\n"
}
] |
2016/12/21
|
[
"https://wordpress.stackexchange.com/questions/249948",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109390/"
] |
My post template won't load the stylesheet, what's going wrong?
```
function wpse_enqueue_post_template_styles() {
if ( is_post_template( 'category-bedrijven.php' ) ) {
wp_enqueue_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );
```
|
You can do it like-
```
function wpse_enqueue_post_template_styles() {
if ( is_category('bedrijven') ) {
wp_enqueue_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );
```
Here ***bedrijven*** is your category slug.
As you said the above method hasn't worked for you, so here I'm suggesting another method-
First remove the first method's full code. Then follow this below method step by step-
**Step 1:**
In your theme's `functions.php` put the below code block-
```
function the_dramatist_register_category_styles() {
wp_register_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
add_action( 'wp_enqueue_scripts', 'the_dramatist_register_category_styles' );
```
By this above code block we are registering your stylesheet file at ***WordPress***. So we can call it anytime.
**Step 2:**
Now go to your `category-bedrijven.php` file and inside this file put the below code-
```
<?php wp_enqueue_style('post-template'); ?>
```
It'll must work if you do it right.
Hope that helps.
|
249,961 |
<p>I am experiencing a really weird issue. </p>
<p>The built in function the_excerpt() as soon as the user inserts a custom excerpt form the back end return the excerpt which is produced dynamically by WP without a read more button. If the user does not insert a custom excerpt, the function returns the excerpt along with a read more button.</p>
<p>I want to have full control of this function. I used the code</p>
<pre><code>if (!function_exists('sociality_excerpt_more')) {
function sociality_excerpt_more($more) {
return $more . '&nbsp<a class="read-more p-color" rel="bookmark" title="'. get_the_title() .'" href="'. get_permalink($post->ID) . '">'. esc_html__('View more','g5plus-handmade') .'<i class="pe-7s-right-arrow"></i></a>';
}
add_filter('the_excerpt', 'sociality_excerpt_more');
}
</code></pre>
<p>but it does not have an effect. Using this snippet the function returns twice a read more button if the user does not insert a custom excerpt.</p>
<p>Any help appreciated :)</p>
|
[
{
"answer_id": 249951,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>You can do it like-</p>\n\n<pre><code>function wpse_enqueue_post_template_styles() {\n if ( is_category('bedrijven') ) {\n wp_enqueue_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );\n</code></pre>\n\n<p>Here <strong><em>bedrijven</em></strong> is your category slug.</p>\n\n<p>As you said the above method hasn't worked for you, so here I'm suggesting another method-</p>\n\n<p>First remove the first method's full code. Then follow this below method step by step-</p>\n\n<p><strong>Step 1:</strong> \nIn your theme's <code>functions.php</code> put the below code block-</p>\n\n<pre><code>function the_dramatist_register_category_styles() {\n wp_register_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'the_dramatist_register_category_styles' );\n</code></pre>\n\n<p>By this above code block we are registering your stylesheet file at <strong><em>WordPress</em></strong>. So we can call it anytime.</p>\n\n<p><strong>Step 2:</strong>\nNow go to your <code>category-bedrijven.php</code> file and inside this file put the below code-</p>\n\n<pre><code><?php wp_enqueue_style('post-template'); ?>\n</code></pre>\n\n<p>It'll must work if you do it right. </p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 249952,
"author": "Mohamed Rihan",
"author_id": 85768,
"author_profile": "https://wordpress.stackexchange.com/users/85768",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function wpse_enqueue_post_template_styles() {\n\n if ( is_page_template( 'category-bedrijven.php' ) ) {\n wp_enqueue_style( 'cat-style', get_stylesheet_directory_uri() . '/layout-interieur.css' ); \n } \n}\n add_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );\n</code></pre>\n"
},
{
"answer_id": 249980,
"author": "Khuram",
"author_id": 109088,
"author_profile": "https://wordpress.stackexchange.com/users/109088",
"pm_score": 0,
"selected": false,
"text": "<p>You can do like this:</p>\n\n<p>$handle = 'wpdocs';</p>\n\n<p>wp_register_style( $handle, </p>\n\n<p>get_stylesheet_directory_uri().'/relative/path/to/stylesheet.css', array(), '', true );</p>\n\n<p>if ( is_page_template( 'template-name.php' ) ) {\n wp_enqueue_style( $handle );\n}</p>\n"
}
] |
2016/12/21
|
[
"https://wordpress.stackexchange.com/questions/249961",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109321/"
] |
I am experiencing a really weird issue.
The built in function the\_excerpt() as soon as the user inserts a custom excerpt form the back end return the excerpt which is produced dynamically by WP without a read more button. If the user does not insert a custom excerpt, the function returns the excerpt along with a read more button.
I want to have full control of this function. I used the code
```
if (!function_exists('sociality_excerpt_more')) {
function sociality_excerpt_more($more) {
return $more . ' <a class="read-more p-color" rel="bookmark" title="'. get_the_title() .'" href="'. get_permalink($post->ID) . '">'. esc_html__('View more','g5plus-handmade') .'<i class="pe-7s-right-arrow"></i></a>';
}
add_filter('the_excerpt', 'sociality_excerpt_more');
}
```
but it does not have an effect. Using this snippet the function returns twice a read more button if the user does not insert a custom excerpt.
Any help appreciated :)
|
You can do it like-
```
function wpse_enqueue_post_template_styles() {
if ( is_category('bedrijven') ) {
wp_enqueue_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse_enqueue_post_template_styles' );
```
Here ***bedrijven*** is your category slug.
As you said the above method hasn't worked for you, so here I'm suggesting another method-
First remove the first method's full code. Then follow this below method step by step-
**Step 1:**
In your theme's `functions.php` put the below code block-
```
function the_dramatist_register_category_styles() {
wp_register_style( 'post-template', get_stylesheet_directory_uri() . '/layout-interieur.css' );
}
add_action( 'wp_enqueue_scripts', 'the_dramatist_register_category_styles' );
```
By this above code block we are registering your stylesheet file at ***WordPress***. So we can call it anytime.
**Step 2:**
Now go to your `category-bedrijven.php` file and inside this file put the below code-
```
<?php wp_enqueue_style('post-template'); ?>
```
It'll must work if you do it right.
Hope that helps.
|
250,032 |
<p>I'm wondering how to get at custom field information attached to a page, not a post.</p>
<p>Using get_post_meta seems like the right idea, but I don't know how to tell the function to look at page ids and not post ids. Also it's no clear to me if this function can work outside the loop.</p>
<p>A short piece of code showing how to access the page custom field would be really useful. </p>
|
[
{
"answer_id": 250034,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 1,
"selected": true,
"text": "<p>Sometimes WordPress is criticized treating everything as a <code>post</code>. The matter of fact is, post type <code>pages</code>, post type <code>post</code> - both are actually Post in database. So no post will collide with any page ID. :)</p>\n\n<p>So simply a <code>get_post_meta()</code> is enough.</p>\n\n<p>But if you still want something specific to Pages, you can use:</p>\n\n<pre><code>if( is_page() ) get_post_meta(...);\n</code></pre>\n\n<p>Yes, you can use <code>get_post_meta()</code> outside the loop. But instead of passing the post_id using <code>get_the_ID()</code> you have to pass the post_id manually.</p>\n"
},
{
"answer_id": 250035,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>Pages, Posts, and Custom Post Types are all stored in the same table with unique IDs, and in the case of meta data it works the same way for all types.</p>\n\n<p>In the loop you can use:</p>\n\n<pre><code>echo get_post_meta( get_the_ID(), 'your_key', true );\n</code></pre>\n\n<p>Or anywhere on a page, <code>get_queried_object_id()</code> will give you the page ID:</p>\n\n<pre><code>echo get_post_meta( get_queried_object_id(), 'your_key', true );\n</code></pre>\n"
}
] |
2016/12/22
|
[
"https://wordpress.stackexchange.com/questions/250032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109442/"
] |
I'm wondering how to get at custom field information attached to a page, not a post.
Using get\_post\_meta seems like the right idea, but I don't know how to tell the function to look at page ids and not post ids. Also it's no clear to me if this function can work outside the loop.
A short piece of code showing how to access the page custom field would be really useful.
|
Sometimes WordPress is criticized treating everything as a `post`. The matter of fact is, post type `pages`, post type `post` - both are actually Post in database. So no post will collide with any page ID. :)
So simply a `get_post_meta()` is enough.
But if you still want something specific to Pages, you can use:
```
if( is_page() ) get_post_meta(...);
```
Yes, you can use `get_post_meta()` outside the loop. But instead of passing the post\_id using `get_the_ID()` you have to pass the post\_id manually.
|
250,041 |
<p>I have created a a site on my localhost, But Now I need to upload website on live server so i need to export word press DB from Phpmyadmin, But I cant find any WP DB there.</p>
<p>Here is my <strong>wp-config file</strong></p>
<pre><code>/** The name of the database for WordPress */
define('DB_NAME', 'bitnami_wordpress');
/** MySQL database username */
define('DB_USER', 'bn_wordpress');
/** MySQL database password */
define('DB_PASSWORD', '0cca6aaab5');
/** MySQL hostname */
define('DB_HOST', 'localhost:3306');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
</code></pre>
<p><strong>phpmyadmin config file</strong></p>
<pre><code>/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '123456';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';
/* Bind to the localhost ipv4 address and tcp */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';
/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['relation'] = 'pma__relation';
$cfg['Servers'][$i]['table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['history'] = 'pma__history';
$cfg['Servers'][$i]['designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['recent'] = 'pma__recent';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['users'] = 'pma__users';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
$cfg['Servers'][$i]['favorite'] = 'pma__favorite';
</code></pre>
<p><strong>Here is my phpmyadmin screenshot</strong> </p>
<p><a href="https://i.stack.imgur.com/EvfLb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EvfLb.png" alt="enter image description here"></a></p>
<p>I have logged in my phpmyadmin through root user, so i have all the privileges (in case)</p>
<p>Can anyone tell me what's the issue here ??</p>
|
[
{
"answer_id": 250043,
"author": "Bunty",
"author_id": 109377,
"author_profile": "https://wordpress.stackexchange.com/users/109377",
"pm_score": 0,
"selected": false,
"text": "<p>There is a plugin named 'adminer'. You can use that.</p>\n\n<p>And my all time favourite for moving wordpress site is \"Duplicator\"</p>\n\n<p>You can get that from : <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/duplicator/</a> </p>\n"
},
{
"answer_id": 311472,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I have a well-tweaked procedure I use to move a site from development to a live site (or from one hosting place to another). </p>\n\n<p>It involves creating a base WP install on the new place, then copying files and data from the old place to the new place. And then using the Better Search and Replace plugin to fix any incorrect URLs in the database. </p>\n\n<p>It's a bit involved (and too long) to post as an answer, but I've used the process many times so it has worked well for me. Look <a href=\"https://securitydawg.com/moving-a-wordpress-site/\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>As for creating a new WP site, most hosting places have a 'wizard' that will create a base WP installation. But then you have to move files and data from development to the new place. </p>\n\n<p>And I have tried many different 'automated' processes to do it, but they weren't always successful, and sometimes required purchase of the premium version to complete the task. So I developed my own process.</p>\n\n<p>You'll also find many other resources/tutorials on the same subject. I used those as a basis for my process, and then added tweaks as I have done more of them.</p>\n"
},
{
"answer_id": 311537,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 1,
"selected": false,
"text": "<p>I don't see any reason to login as root if you only need the one database... Have you tried logging in to phpMyAdmin as the user with the same credentials as your WordPress installation? </p>\n\n<pre><code>user: bn_wordpress\npass: 0cca6aaab5\nport: 3306\n</code></pre>\n\n<p>We could avoid phpMyAdmin all together... From the command line you can dump the database using the following:</p>\n\n<pre><code>mysqldump -u [uname] -p[pass] db_name > db_backup.sql\n</code></pre>\n\n<p>A simpler *(more user-friendly/non-technical) being to dump the db via wp-admin using a backup/export plugin.</p>\n\n<p>I'm partial to WP-Migrate DB for small dumps like this, but duplicator, all export pro, any of the WordPress backup/migration plugins can do the job of dumping your MySQL data for you.</p>\n"
}
] |
2016/12/22
|
[
"https://wordpress.stackexchange.com/questions/250041",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101083/"
] |
I have created a a site on my localhost, But Now I need to upload website on live server so i need to export word press DB from Phpmyadmin, But I cant find any WP DB there.
Here is my **wp-config file**
```
/** The name of the database for WordPress */
define('DB_NAME', 'bitnami_wordpress');
/** MySQL database username */
define('DB_USER', 'bn_wordpress');
/** MySQL database password */
define('DB_PASSWORD', '0cca6aaab5');
/** MySQL hostname */
define('DB_HOST', 'localhost:3306');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
```
**phpmyadmin config file**
```
/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '123456';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';
/* Bind to the localhost ipv4 address and tcp */
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';
/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma__bookmark';
$cfg['Servers'][$i]['relation'] = 'pma__relation';
$cfg['Servers'][$i]['table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['history'] = 'pma__history';
$cfg['Servers'][$i]['designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['recent'] = 'pma__recent';
$cfg['Servers'][$i]['table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['users'] = 'pma__users';
$cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
$cfg['Servers'][$i]['favorite'] = 'pma__favorite';
```
**Here is my phpmyadmin screenshot**
[](https://i.stack.imgur.com/EvfLb.png)
I have logged in my phpmyadmin through root user, so i have all the privileges (in case)
Can anyone tell me what's the issue here ??
|
I don't see any reason to login as root if you only need the one database... Have you tried logging in to phpMyAdmin as the user with the same credentials as your WordPress installation?
```
user: bn_wordpress
pass: 0cca6aaab5
port: 3306
```
We could avoid phpMyAdmin all together... From the command line you can dump the database using the following:
```
mysqldump -u [uname] -p[pass] db_name > db_backup.sql
```
A simpler \*(more user-friendly/non-technical) being to dump the db via wp-admin using a backup/export plugin.
I'm partial to WP-Migrate DB for small dumps like this, but duplicator, all export pro, any of the WordPress backup/migration plugins can do the job of dumping your MySQL data for you.
|
250,051 |
<p>I have a query that works when I have a field view_type = sale but when the view_type = lead it doesn't return any records even when I know there is one. Here is the query...</p>
<pre><code> SELECT a.id, a.user_email, a.user_registered, a.user_login, b1.meta_value AS first_name, b2.meta_value as last_name, b3.meta_value as qualified,
b4.meta_value as referrer,
b5.meta_value as view_type,
b6.meta_value as ref_by,
b7.meta_value as wp_optimizemember_custom_fields
FROM wp_users a
INNER JOIN wp_usermeta b1 ON b1.user_id = a.ID AND b1.meta_key = 'first_name'
INNER JOIN wp_usermeta b2 ON b2.user_id = a.ID AND b2.meta_key = 'last_name'
INNER JOIN wp_usermeta b3 ON b3.user_id = a.ID AND b3.meta_key = 'qualified'
INNER JOIN wp_usermeta b4 ON b4.user_id = a.ID AND b4.meta_key = 'referrer'
INNER JOIN wp_usermeta b5 ON b5.user_id = a.ID AND b5.meta_key = 'view_type'
INNER JOIN wp_usermeta b6 ON b6.user_id = a.ID AND b6.meta_key = 'ref_by'
INNER JOIN wp_usermeta b7 ON b7.user_id = a.ID AND b7.meta_key = 'wp_optimizemember_custom_fields'
WHERE (b4.meta_value LIKE '$user_ID' AND b5.meta_value LIKE 'lead') or
(b6.meta_value LIKE '$user_ID' AND b5.meta_value LIKE 'lead')
</code></pre>
<p>What wrong with this query?</p>
|
[
{
"answer_id": 250043,
"author": "Bunty",
"author_id": 109377,
"author_profile": "https://wordpress.stackexchange.com/users/109377",
"pm_score": 0,
"selected": false,
"text": "<p>There is a plugin named 'adminer'. You can use that.</p>\n\n<p>And my all time favourite for moving wordpress site is \"Duplicator\"</p>\n\n<p>You can get that from : <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/duplicator/</a> </p>\n"
},
{
"answer_id": 311472,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I have a well-tweaked procedure I use to move a site from development to a live site (or from one hosting place to another). </p>\n\n<p>It involves creating a base WP install on the new place, then copying files and data from the old place to the new place. And then using the Better Search and Replace plugin to fix any incorrect URLs in the database. </p>\n\n<p>It's a bit involved (and too long) to post as an answer, but I've used the process many times so it has worked well for me. Look <a href=\"https://securitydawg.com/moving-a-wordpress-site/\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>As for creating a new WP site, most hosting places have a 'wizard' that will create a base WP installation. But then you have to move files and data from development to the new place. </p>\n\n<p>And I have tried many different 'automated' processes to do it, but they weren't always successful, and sometimes required purchase of the premium version to complete the task. So I developed my own process.</p>\n\n<p>You'll also find many other resources/tutorials on the same subject. I used those as a basis for my process, and then added tweaks as I have done more of them.</p>\n"
},
{
"answer_id": 311537,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 1,
"selected": false,
"text": "<p>I don't see any reason to login as root if you only need the one database... Have you tried logging in to phpMyAdmin as the user with the same credentials as your WordPress installation? </p>\n\n<pre><code>user: bn_wordpress\npass: 0cca6aaab5\nport: 3306\n</code></pre>\n\n<p>We could avoid phpMyAdmin all together... From the command line you can dump the database using the following:</p>\n\n<pre><code>mysqldump -u [uname] -p[pass] db_name > db_backup.sql\n</code></pre>\n\n<p>A simpler *(more user-friendly/non-technical) being to dump the db via wp-admin using a backup/export plugin.</p>\n\n<p>I'm partial to WP-Migrate DB for small dumps like this, but duplicator, all export pro, any of the WordPress backup/migration plugins can do the job of dumping your MySQL data for you.</p>\n"
}
] |
2016/12/22
|
[
"https://wordpress.stackexchange.com/questions/250051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88860/"
] |
I have a query that works when I have a field view\_type = sale but when the view\_type = lead it doesn't return any records even when I know there is one. Here is the query...
```
SELECT a.id, a.user_email, a.user_registered, a.user_login, b1.meta_value AS first_name, b2.meta_value as last_name, b3.meta_value as qualified,
b4.meta_value as referrer,
b5.meta_value as view_type,
b6.meta_value as ref_by,
b7.meta_value as wp_optimizemember_custom_fields
FROM wp_users a
INNER JOIN wp_usermeta b1 ON b1.user_id = a.ID AND b1.meta_key = 'first_name'
INNER JOIN wp_usermeta b2 ON b2.user_id = a.ID AND b2.meta_key = 'last_name'
INNER JOIN wp_usermeta b3 ON b3.user_id = a.ID AND b3.meta_key = 'qualified'
INNER JOIN wp_usermeta b4 ON b4.user_id = a.ID AND b4.meta_key = 'referrer'
INNER JOIN wp_usermeta b5 ON b5.user_id = a.ID AND b5.meta_key = 'view_type'
INNER JOIN wp_usermeta b6 ON b6.user_id = a.ID AND b6.meta_key = 'ref_by'
INNER JOIN wp_usermeta b7 ON b7.user_id = a.ID AND b7.meta_key = 'wp_optimizemember_custom_fields'
WHERE (b4.meta_value LIKE '$user_ID' AND b5.meta_value LIKE 'lead') or
(b6.meta_value LIKE '$user_ID' AND b5.meta_value LIKE 'lead')
```
What wrong with this query?
|
I don't see any reason to login as root if you only need the one database... Have you tried logging in to phpMyAdmin as the user with the same credentials as your WordPress installation?
```
user: bn_wordpress
pass: 0cca6aaab5
port: 3306
```
We could avoid phpMyAdmin all together... From the command line you can dump the database using the following:
```
mysqldump -u [uname] -p[pass] db_name > db_backup.sql
```
A simpler \*(more user-friendly/non-technical) being to dump the db via wp-admin using a backup/export plugin.
I'm partial to WP-Migrate DB for small dumps like this, but duplicator, all export pro, any of the WordPress backup/migration plugins can do the job of dumping your MySQL data for you.
|
250,076 |
<p><a href="https://stackoverflow.com/questions/4915753/how-can-i-remove-3-characters-at-the-end-of-a-string-in-php">This snippet</a> shows us how to remove 3 characters at the end of a string...</p>
<pre><code>echo substr($string, 0, -3);
</code></pre>
<p>I'd like to find a way to use a custom field value as the string. This is what I've tried with no luck...</p>
<pre><code>echo substr( get_post_meta( $post->ID, "CUSTOMFIELD", true ), 0, -3 );
</code></pre>
|
[
{
"answer_id": 250078,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": true,
"text": "<p>You have to consider that you're dealing with <a href=\"http://php.net/manual/en/function.substr.php\" rel=\"nofollow noreferrer\"><code>substr()</code></a> a <em>string</em> related function as the <strong>str</strong> in the function name indicates. That does mean that the parameter <code>$string</code> you give actually has to be of the <a href=\"http://php.net/manual/en/language.types.intro.php\" rel=\"nofollow noreferrer\">type <code>string</code></a>.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta()</code></a> on the other hand does just give you back whatever type you saved in the first place. So it isn't guaranteed that your getting back a string - you have to make sure of that yourself. Which you can do by <a href=\"http://php.net/manual/en/language.types.type-juggling.php\" rel=\"nofollow noreferrer\">type casting</a> the value, variable you receive.</p>\n\n<p>So far so good, let's put it together:</p>\n\n<pre><code>$custom_field = (string) get_post_meta( $post->ID, \"CUSTOMFIELD\", true ); \necho substr( $custom_field, 0, -3 );\n</code></pre>\n"
},
{
"answer_id": 250079,
"author": "Omar Elsayed",
"author_id": 109382,
"author_profile": "https://wordpress.stackexchange.com/users/109382",
"pm_score": 2,
"selected": false,
"text": "<p>You can use string casting (<a href=\"http://php.net/manual/en/language.types.string.php\" rel=\"nofollow noreferrer\">string</a>)</p>\n\n<pre><code>$str = (string) get_post_meta($post->ID, \"CUSTOMFIELD\", true);\necho substr( $str, 0, -3 );\n</code></pre>\n"
}
] |
2016/12/22
|
[
"https://wordpress.stackexchange.com/questions/250076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] |
[This snippet](https://stackoverflow.com/questions/4915753/how-can-i-remove-3-characters-at-the-end-of-a-string-in-php) shows us how to remove 3 characters at the end of a string...
```
echo substr($string, 0, -3);
```
I'd like to find a way to use a custom field value as the string. This is what I've tried with no luck...
```
echo substr( get_post_meta( $post->ID, "CUSTOMFIELD", true ), 0, -3 );
```
|
You have to consider that you're dealing with [`substr()`](http://php.net/manual/en/function.substr.php) a *string* related function as the **str** in the function name indicates. That does mean that the parameter `$string` you give actually has to be of the [type `string`](http://php.net/manual/en/language.types.intro.php).
[`get_post_meta()`](https://developer.wordpress.org/reference/functions/get_post_meta/) on the other hand does just give you back whatever type you saved in the first place. So it isn't guaranteed that your getting back a string - you have to make sure of that yourself. Which you can do by [type casting](http://php.net/manual/en/language.types.type-juggling.php) the value, variable you receive.
So far so good, let's put it together:
```
$custom_field = (string) get_post_meta( $post->ID, "CUSTOMFIELD", true );
echo substr( $custom_field, 0, -3 );
```
|
250,102 |
<p>I've mistakenly deleted the <strong><code>functions.php</code></strong> file of my Twenty Sixteen WordPress Theme running the command below:</p>
<pre><code>rm /var/www/html/wp/wp-content/themes/twentysixteen/functions.php
</code></pre>
<p>The Twenty Sixteen Theme is my currently active theme and as such, my WordPress site is no longer accessible as it used to be <em>(ref. screenshot below)</em>.</p>
<p><a href="https://i.stack.imgur.com/Ei2ur.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ei2ur.png" alt="enter image description here"></a></p>
<p>How do I fix it?</p>
|
[
{
"answer_id": 250108,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 0,
"selected": false,
"text": "<p>You can always re-download the Twenty Sixteen theme from the official <a href=\"https://wordpress.org/themes/twentysixteen/\" rel=\"nofollow noreferrer\"><strong>Theme Directory</strong></a> and restore the functions.php file. You'll lose any edits you have made to the previous file</p>\n"
},
{
"answer_id": 250109,
"author": "nyedidikeke",
"author_id": 105480,
"author_profile": "https://wordpress.stackexchange.com/users/105480",
"pm_score": 2,
"selected": true,
"text": "<p>To fix your site, you should get another <a href=\"https://github.com/WordPress/twentysixteen/blob/master/functions.php\" rel=\"nofollow noreferrer\"><strong><code>functions.php</code></strong></a>.</p>\n\n<p>As such, you can get that from your most recent and operational backup and upload it unto the location of the mistakenly deleted one.</p>\n\n<p>In case you don't have a backup, your last option will be to download a fresh copy of your <a href=\"https://downloads.wordpress.org/theme/twentysixteen.1.3.zip\" rel=\"nofollow noreferrer\" title=\"Download the Twenty Sixteen WordPress Theme\">theme</a>; once that done, extract and upload the <strong><code>functions.php</code></strong> file it contains unto the location of the one you've mistakenly deleted from your server.</p>\n\n<p>In the later case (should you have edited directly your <strong><code>functions.php</code></strong> - <em>which is not a recommended practice</em>), you cannot recover any previous modifications performed on the file.</p>\n\n<p><em>Should you consider editing the Twenty Sixteen WordPress Theme or any other one from the <a href=\"https://wordpress.org/themes/\" rel=\"nofollow noreferrer\">WordPress Repository</a> or any other source, I will recommend you create a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\" title=\"Get started with WordPress Child Themes\">Child Theme</a> of the theme you intended to use for that purpose, rather than editing the actual theme directly.</em></p>\n"
}
] |
2016/12/22
|
[
"https://wordpress.stackexchange.com/questions/250102",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70405/"
] |
I've mistakenly deleted the **`functions.php`** file of my Twenty Sixteen WordPress Theme running the command below:
```
rm /var/www/html/wp/wp-content/themes/twentysixteen/functions.php
```
The Twenty Sixteen Theme is my currently active theme and as such, my WordPress site is no longer accessible as it used to be *(ref. screenshot below)*.
[](https://i.stack.imgur.com/Ei2ur.png)
How do I fix it?
|
To fix your site, you should get another [**`functions.php`**](https://github.com/WordPress/twentysixteen/blob/master/functions.php).
As such, you can get that from your most recent and operational backup and upload it unto the location of the mistakenly deleted one.
In case you don't have a backup, your last option will be to download a fresh copy of your [theme](https://downloads.wordpress.org/theme/twentysixteen.1.3.zip "Download the Twenty Sixteen WordPress Theme"); once that done, extract and upload the **`functions.php`** file it contains unto the location of the one you've mistakenly deleted from your server.
In the later case (should you have edited directly your **`functions.php`** - *which is not a recommended practice*), you cannot recover any previous modifications performed on the file.
*Should you consider editing the Twenty Sixteen WordPress Theme or any other one from the [WordPress Repository](https://wordpress.org/themes/) or any other source, I will recommend you create a [Child Theme](https://codex.wordpress.org/Child_Themes "Get started with WordPress Child Themes") of the theme you intended to use for that purpose, rather than editing the actual theme directly.*
|
250,147 |
<p>I need your help.</p>
<p>There is my problem: I have custom post type "Player". And this <em>CPT</em> has custom field "Seasons". Seasons can have multiple values separated by comma - for example "2014,2015,2016" etc.</p>
<p>Now I need filter list of player who played in certain seasons - for example 2015 and 2016.</p>
<p>And now I need your help with this <code>wp_query</code>. I try this code, but it do not work :-/</p>
<pre><code>query_posts(
array(
'post_type' => 'player',
'meta_query' => array(
array(
'key' => 'seasons',
'value' => array( '2015','2016'),
'compare' => 'IN',
),
),
)
);
</code></pre>
<p>Please help.</p>
<p>Thanks, <br>
libor</p>
|
[
{
"answer_id": 250182,
"author": "dgarceran",
"author_id": 109222,
"author_profile": "https://wordpress.stackexchange.com/users/109222",
"pm_score": 0,
"selected": false,
"text": "<p>Here's how I would do it with <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The Loop</a> and using <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">Codex examples</a>.</p>\n\n<pre><code>$args = array(\n 'post_type' => 'player',\n 'meta_key' => 'age',\n 'meta_query' => array(\n array(\n 'key' => 'seasons',\n 'value' => array( 2015, 2016 ), // or array( '2015', '2016' )\n 'compare' => 'IN',\n ),\n ),\n);\n// The Query\n$query = new WP_Query( $args );\n\n// The Loop\nif ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n // do something\n }\n} else {\n // no posts found\n}\n\n// Restore original Post Data\nwp_reset_postdata();\n</code></pre>\n\n<p>Your problem is that you're adding values in one string like \"2015,2016,2017\"... and you should separate every value in a different field. With <a href=\"https://www.advancedcustomfields.com/\" rel=\"nofollow noreferrer\">ACF</a> you have the option of adding a repeater of seasons, and you can also do a <a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow noreferrer\">custom taxonomy</a> to save these values, instead than a post meta. If you don't want to change that, you should retrieve your post meta data first with <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">get_post_meta</a>, and use <a href=\"http://php.net/manual/en/function.explode.php\" rel=\"nofollow noreferrer\">explode</a> with PHP.</p>\n"
},
{
"answer_id": 279958,
"author": "Michael Mizner",
"author_id": 81179,
"author_profile": "https://wordpress.stackexchange.com/users/81179",
"pm_score": 2,
"selected": false,
"text": "<p>Expanding a bit on the answer from @dgarceran</p>\n\n<p>Generally, using the <code>WP_Query</code> class is probably a good idea for querying posts.</p>\n\n<p>We'll want to pass arguments to that query. </p>\n\n<p>In your case we'll likely want use one of the following:</p>\n\n<ol>\n<li>\"<strong>Custom Field Parameters</strong>\" - <code>meta_query</code> </li>\n<li>\"<strong>Taxonomy Parameters</strong>\" - <code>tax_query</code> </li>\n</ol>\n\n<p>For a nearly comprehensive example of all the options I like to reference this gist: <a href=\"https://gist.github.com/luetkemj/2023628\" rel=\"nofollow noreferrer\">https://gist.github.com/luetkemj/2023628</a>. </p>\n\n<p>Also see the Codex: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n\n<p>Both take an array of associative arrays e.g.</p>\n\n<p><strong>Note</strong>: I'll be using syntax that is compatible with as of PHP 5.4</p>\n\n<pre><code> $meta_query_args = [\n [\n 'key' => 'season',\n 'value' => [ '2015', '2016' ],\n 'compare' => 'IN',\n ],\n ];\n</code></pre>\n\n<p>We can bring those arguments into our instance of <code>WP_Query</code></p>\n\n<pre><code> $args = [\n 'post_type' => 'player',\n 'posts_per_page' => 100, // Set this to a reasonable limit\n 'meta_query' => $meta_query_args,\n\n ];\n\n $the_query = new WP_Query( $args );\n</code></pre>\n\n<p>What's happenning at this point is WordPress is going to check all posts that match your <strong>custom post type</strong> <code>player</code>. Then, it will query the metadata you've set with key <code>season</code>. Any posts matching <code>2015</code> or <code>2016</code> will be returned.</p>\n\n<p><strong>Note:</strong> using <code>meta_query</code> this way isn't generally recommended because it's a little heavy on the database. The consensus seems to be that querying taxonomies is more performant (don't quote me on that, couldn't find my source)</p>\n\n<p>So for a quick alternative, I reccomend the following example:</p>\n\n<pre><code> $tax_query_args = [\n [\n 'taxonomy' => 'season',\n 'field' => 'slug',\n 'terms' => [ '2015', '2016' ],\n 'operator' => 'IN',\n ],\n ];\n\n $args = [\n 'post_type' => 'player',\n 'posts_per_page' => 100, // Set this to a reasonable limit\n 'tax_query' => $tax_query_args,\n ];\n\n $the_query = new WP_Query( $args );\n</code></pre>\n\n<p>Now we can actually loop through the data, here's some example markup:</p>\n\n<pre><code> <section class=\"season-list\">\n <?php while ( $the_query->have_posts() ) : $the_query->the_post();\n $post_id = get_the_ID();\n // $season = get_post_meta( $post_id, 'season', true ); // example if you are still going to use post meta\n $season = wp_get_object_terms( $post_id, 'season', [ 'fields' => 'names' ] );\n ?>\n\n <h3><?php the_title(); ?></h3>\n <p><?php echo __( 'Season: ' ) . sanitize_text_field( implode( $season ) ); ?></p>\n\n <?php endwhile; ?>\n </section>\n</code></pre>\n\n<p>When you use <code>WP_Query</code> especially in templates, make sure you end with <code>wp_reset_postdata();</code></p>\n\n<p>Putting it altogether (tl;dr)</p>\n\n<pre><code> $tax_query_args = [\n [\n 'taxonomy' => 'season',\n 'field' => 'slug',\n 'terms' => [ '2015', '2016' ],\n 'operator' => 'IN',\n ],\n ];\n\n $args = [\n 'post_type' => 'player',\n 'posts_per_page' => 100, // Set this to a reasonable limit\n 'tax_query' => $tax_query_args,\n ];\n\n $the_query = new WP_Query( $args );\n\n ?>\n <section class=\"season-list\">\n <?php while ( $the_query->have_posts() ) : $the_query->the_post();\n $post_id = get_the_ID();\n // $season = get_post_meta( $post_id, 'season', true ); // example if you are still going to use post meta\n $season = wp_get_object_terms( $post_id, 'season', [ 'fields' => 'names' ] );\n ?>\n\n <h3><?php the_title(); ?></h3>\n <p><?php echo __( 'Season: ' ) . sanitize_text_field( implode( $season ) ); ?></p>\n\n <?php endwhile; ?>\n </section>\n <?php\n\n wp_reset_postdata();\n</code></pre>\n\n<p><strong>Front-end view of our query:</strong>\n<a href=\"https://i.stack.imgur.com/o5Cr8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/o5Cr8.png\" alt=\"Example Front End\"></a>\n<strong>Dashboard view of CPT Player posts:</strong>\n<a href=\"https://i.stack.imgur.com/k74ej.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/k74ej.png\" alt=\"Example CPT Player posts\"></a></p>\n\n<p>Hope that provides a bit of context </p>\n"
}
] |
2016/12/23
|
[
"https://wordpress.stackexchange.com/questions/250147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63734/"
] |
I need your help.
There is my problem: I have custom post type "Player". And this *CPT* has custom field "Seasons". Seasons can have multiple values separated by comma - for example "2014,2015,2016" etc.
Now I need filter list of player who played in certain seasons - for example 2015 and 2016.
And now I need your help with this `wp_query`. I try this code, but it do not work :-/
```
query_posts(
array(
'post_type' => 'player',
'meta_query' => array(
array(
'key' => 'seasons',
'value' => array( '2015','2016'),
'compare' => 'IN',
),
),
)
);
```
Please help.
Thanks,
libor
|
Expanding a bit on the answer from @dgarceran
Generally, using the `WP_Query` class is probably a good idea for querying posts.
We'll want to pass arguments to that query.
In your case we'll likely want use one of the following:
1. "**Custom Field Parameters**" - `meta_query`
2. "**Taxonomy Parameters**" - `tax_query`
For a nearly comprehensive example of all the options I like to reference this gist: <https://gist.github.com/luetkemj/2023628>.
Also see the Codex: <https://codex.wordpress.org/Class_Reference/WP_Query>
Both take an array of associative arrays e.g.
**Note**: I'll be using syntax that is compatible with as of PHP 5.4
```
$meta_query_args = [
[
'key' => 'season',
'value' => [ '2015', '2016' ],
'compare' => 'IN',
],
];
```
We can bring those arguments into our instance of `WP_Query`
```
$args = [
'post_type' => 'player',
'posts_per_page' => 100, // Set this to a reasonable limit
'meta_query' => $meta_query_args,
];
$the_query = new WP_Query( $args );
```
What's happenning at this point is WordPress is going to check all posts that match your **custom post type** `player`. Then, it will query the metadata you've set with key `season`. Any posts matching `2015` or `2016` will be returned.
**Note:** using `meta_query` this way isn't generally recommended because it's a little heavy on the database. The consensus seems to be that querying taxonomies is more performant (don't quote me on that, couldn't find my source)
So for a quick alternative, I reccomend the following example:
```
$tax_query_args = [
[
'taxonomy' => 'season',
'field' => 'slug',
'terms' => [ '2015', '2016' ],
'operator' => 'IN',
],
];
$args = [
'post_type' => 'player',
'posts_per_page' => 100, // Set this to a reasonable limit
'tax_query' => $tax_query_args,
];
$the_query = new WP_Query( $args );
```
Now we can actually loop through the data, here's some example markup:
```
<section class="season-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$post_id = get_the_ID();
// $season = get_post_meta( $post_id, 'season', true ); // example if you are still going to use post meta
$season = wp_get_object_terms( $post_id, 'season', [ 'fields' => 'names' ] );
?>
<h3><?php the_title(); ?></h3>
<p><?php echo __( 'Season: ' ) . sanitize_text_field( implode( $season ) ); ?></p>
<?php endwhile; ?>
</section>
```
When you use `WP_Query` especially in templates, make sure you end with `wp_reset_postdata();`
Putting it altogether (tl;dr)
```
$tax_query_args = [
[
'taxonomy' => 'season',
'field' => 'slug',
'terms' => [ '2015', '2016' ],
'operator' => 'IN',
],
];
$args = [
'post_type' => 'player',
'posts_per_page' => 100, // Set this to a reasonable limit
'tax_query' => $tax_query_args,
];
$the_query = new WP_Query( $args );
?>
<section class="season-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$post_id = get_the_ID();
// $season = get_post_meta( $post_id, 'season', true ); // example if you are still going to use post meta
$season = wp_get_object_terms( $post_id, 'season', [ 'fields' => 'names' ] );
?>
<h3><?php the_title(); ?></h3>
<p><?php echo __( 'Season: ' ) . sanitize_text_field( implode( $season ) ); ?></p>
<?php endwhile; ?>
</section>
<?php
wp_reset_postdata();
```
**Front-end view of our query:**
[](https://i.stack.imgur.com/o5Cr8.png)
**Dashboard view of CPT Player posts:**
[](https://i.stack.imgur.com/k74ej.png)
Hope that provides a bit of context
|
250,150 |
<p>I've got an array of images attached to a post, and can output them sequentually just fine:</p>
<p>1 2 3 4 5 6 7</p>
<p>How can I get three images at a time from the array, then step one image forward to create the following arrays of three images:</p>
<p>1 2 3</p>
<p>2 3 4</p>
<p>3 4 5</p>
<p>4 5 6</p>
<p>and so on?</p>
<p>Here's my code:</p>
<pre><code>global $rental;
$images = get_children( array(
'post_parent' => $rental_id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID'
) );
if ($images) :
$i = 0;
foreach ($images as $attachment_id => $image) :
$i++;
$img_url = wp_get_attachment_url( $image->ID );
?>
<div class="item <?php if($i == 1){echo ' active';} ?> class="<?php echo $i; ?>"">
<img src="<?php echo $img_url; ?>" title="<?php echo $i; ?>" />
</div>
<?php endforeach; ?>
<?php endif;
</code></pre>
|
[
{
"answer_id": 250158,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 3,
"selected": true,
"text": "<p>You can split your array using the following</p>\n\n<pre><code>$array = array(1,2,3,4,5,6);\n$number_of_elements = 3;\n\n$count = count( $array );\n$split = array();\nfor ( $i = 0; $i <= $count - 1; $i++ ) {\n $slices = array_slice( $array, $i , $number_of_elements);\n if ( count( $slices ) != $number_of_elements )\n break;\n\n $split[] = $slices;\n}\n\nprint_r( $split );\n</code></pre>\n"
},
{
"answer_id": 251780,
"author": "EHerman",
"author_id": 43000,
"author_profile": "https://wordpress.stackexchange.com/users/43000",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"http://php.net/manual/en/function.array-chunk.php\" rel=\"nofollow noreferrer\">array_chunk</a> for a more elegant solution.</p>\n\n<p>Example:</p>\n\n<pre><code>$array = array( 1, 2, 3, 4, 5, 6, 7, 8, 9 );\n\n$chunks = array_chunk( $array, 3 );\n</code></pre>\n\n<p>The value of <code>$chunks</code> in the example above would be:</p>\n\n<pre><code>Array\n(\n [0] => Array\n (\n [0] => 1\n [1] => 2\n [2] => 3\n )\n\n [1] => Array\n (\n [0] => 4\n [1] => 5\n [2] => 6\n )\n\n [2] => Array\n (\n [0] => 7\n [1] => 8\n [2] => 9\n )\n\n)\n</code></pre>\n\n<p>Short and sweet without the need for any loops.</p>\n"
}
] |
2016/12/23
|
[
"https://wordpress.stackexchange.com/questions/250150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109355/"
] |
I've got an array of images attached to a post, and can output them sequentually just fine:
1 2 3 4 5 6 7
How can I get three images at a time from the array, then step one image forward to create the following arrays of three images:
1 2 3
2 3 4
3 4 5
4 5 6
and so on?
Here's my code:
```
global $rental;
$images = get_children( array(
'post_parent' => $rental_id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID'
) );
if ($images) :
$i = 0;
foreach ($images as $attachment_id => $image) :
$i++;
$img_url = wp_get_attachment_url( $image->ID );
?>
<div class="item <?php if($i == 1){echo ' active';} ?> class="<?php echo $i; ?>"">
<img src="<?php echo $img_url; ?>" title="<?php echo $i; ?>" />
</div>
<?php endforeach; ?>
<?php endif;
```
|
You can split your array using the following
```
$array = array(1,2,3,4,5,6);
$number_of_elements = 3;
$count = count( $array );
$split = array();
for ( $i = 0; $i <= $count - 1; $i++ ) {
$slices = array_slice( $array, $i , $number_of_elements);
if ( count( $slices ) != $number_of_elements )
break;
$split[] = $slices;
}
print_r( $split );
```
|
250,164 |
<p>I'm trying to do a count for pagination and its returning NULL why the query returns results correctly. In this case $total returns NULL which is not correct why? (I didn't include the $args as they work)</p>
<pre><code>$total_query = "SELECT COUNT(*) FROM (${args}) AS total_count";
$total = $wpdb->get_var( $total_query );
$items_per_page = 5;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$results = $wpdb->get_results( $args . " ORDER BY user_registered DESC LIMIT ${offset}, ${items_per_page}" );
</code></pre>
|
[
{
"answer_id": 250158,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 3,
"selected": true,
"text": "<p>You can split your array using the following</p>\n\n<pre><code>$array = array(1,2,3,4,5,6);\n$number_of_elements = 3;\n\n$count = count( $array );\n$split = array();\nfor ( $i = 0; $i <= $count - 1; $i++ ) {\n $slices = array_slice( $array, $i , $number_of_elements);\n if ( count( $slices ) != $number_of_elements )\n break;\n\n $split[] = $slices;\n}\n\nprint_r( $split );\n</code></pre>\n"
},
{
"answer_id": 251780,
"author": "EHerman",
"author_id": 43000,
"author_profile": "https://wordpress.stackexchange.com/users/43000",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"http://php.net/manual/en/function.array-chunk.php\" rel=\"nofollow noreferrer\">array_chunk</a> for a more elegant solution.</p>\n\n<p>Example:</p>\n\n<pre><code>$array = array( 1, 2, 3, 4, 5, 6, 7, 8, 9 );\n\n$chunks = array_chunk( $array, 3 );\n</code></pre>\n\n<p>The value of <code>$chunks</code> in the example above would be:</p>\n\n<pre><code>Array\n(\n [0] => Array\n (\n [0] => 1\n [1] => 2\n [2] => 3\n )\n\n [1] => Array\n (\n [0] => 4\n [1] => 5\n [2] => 6\n )\n\n [2] => Array\n (\n [0] => 7\n [1] => 8\n [2] => 9\n )\n\n)\n</code></pre>\n\n<p>Short and sweet without the need for any loops.</p>\n"
}
] |
2016/12/23
|
[
"https://wordpress.stackexchange.com/questions/250164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88860/"
] |
I'm trying to do a count for pagination and its returning NULL why the query returns results correctly. In this case $total returns NULL which is not correct why? (I didn't include the $args as they work)
```
$total_query = "SELECT COUNT(*) FROM (${args}) AS total_count";
$total = $wpdb->get_var( $total_query );
$items_per_page = 5;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$results = $wpdb->get_results( $args . " ORDER BY user_registered DESC LIMIT ${offset}, ${items_per_page}" );
```
|
You can split your array using the following
```
$array = array(1,2,3,4,5,6);
$number_of_elements = 3;
$count = count( $array );
$split = array();
for ( $i = 0; $i <= $count - 1; $i++ ) {
$slices = array_slice( $array, $i , $number_of_elements);
if ( count( $slices ) != $number_of_elements )
break;
$split[] = $slices;
}
print_r( $split );
```
|
250,167 |
<p>I am trying to update the value of one custom post type's meta when another custom post type is deleted.</p>
<p>When a space_rental is deleted, I need to update some meta value on a space.</p>
<p>I don't think I can use <code>delete_post</code> because it fires after the meta data has been deleted, but this isn't working for me either (either on trashing the post or emptying the trash).</p>
<p>Here is the function and below that is the structure of the meta data for each post type.</p>
<pre><code>//When a space_rental is deleted, we release the space slots they had saved
add_action( 'before_delete_post', 'tps_delete_space_rental' );
function tps_delete_space_rental( $postid ){
if (get_post_type($postid) != 'space_rental') {
return;
}
//Loop through the selected slots in the rental
$selectedSlots = get_post_meta($postid, 'selectedSlots', true);
foreach ($selectedSlots as $slot) {
$spaceSlots = get_post_meta($slot['spaceid'], 'allSlots', true);
//Loop through the slots in the space and find the ones that have the rentalID set to the deleted post
foreach ($spaceSlots as $sSlot) {
if($postid == $sSlot['details']['rentalID']) {
$sSlot['details']['slotStatus'] = 'open';
}
}
}
}
</code></pre>
<p>The 'space' post_type meta is stored like this:</p>
<pre><code>allSlots => array(
'timestamp' => '123456789', //timestamp representing this slot
'details' => array(
'slotStatus' => 'open', //this is either open or filled
'slotUser' => 123, //The ID of the user who owns the rental using this slot
'rentalID' => 345, //The post_id of the 'space_rental' that is using this slot
),
);
</code></pre>
<p>This 'space_rental' post_type meta is stored like this:</p>
<pre><code>selectedSlots => array(
'spaceSlots' => array(
123456789, 654321987, 9876432654, etc...,// An array of timestamps in this rental
),
'spaceid' => 789, //The post_id of the 'space' where this rental is
);
</code></pre>
|
[
{
"answer_id": 250176,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>There's a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post\" rel=\"nofollow noreferrer\"><strong>trash post</strong></a> hook</p>\n\n<pre><code>add_action( 'trash_post', 'my_func' );\nfunction my_func( $postid ){\n\n // We check if the global post type isn't ours and just return\n global $post_type; \n if ( $post_type != 'my_custom_post_type' ) return;\n\n // My custom stuff for deleting my custom post type here\n}\n</code></pre>\n"
},
{
"answer_id": 250193,
"author": "sdx11",
"author_id": 106577,
"author_profile": "https://wordpress.stackexchange.com/users/106577",
"pm_score": 0,
"selected": false,
"text": "<p>if you want to to catch it when user delete( means click trash on post) \nthen possible solution is to use <strong>trash_post</strong> hook</p>\n\n<pre><code>add_action( 'trash_post', 'my_func_before_trash',999,1);\n\nfunction my_func_before_trash($postid){\n //my custom code\n}\n</code></pre>\n"
}
] |
2016/12/23
|
[
"https://wordpress.stackexchange.com/questions/250167",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23492/"
] |
I am trying to update the value of one custom post type's meta when another custom post type is deleted.
When a space\_rental is deleted, I need to update some meta value on a space.
I don't think I can use `delete_post` because it fires after the meta data has been deleted, but this isn't working for me either (either on trashing the post or emptying the trash).
Here is the function and below that is the structure of the meta data for each post type.
```
//When a space_rental is deleted, we release the space slots they had saved
add_action( 'before_delete_post', 'tps_delete_space_rental' );
function tps_delete_space_rental( $postid ){
if (get_post_type($postid) != 'space_rental') {
return;
}
//Loop through the selected slots in the rental
$selectedSlots = get_post_meta($postid, 'selectedSlots', true);
foreach ($selectedSlots as $slot) {
$spaceSlots = get_post_meta($slot['spaceid'], 'allSlots', true);
//Loop through the slots in the space and find the ones that have the rentalID set to the deleted post
foreach ($spaceSlots as $sSlot) {
if($postid == $sSlot['details']['rentalID']) {
$sSlot['details']['slotStatus'] = 'open';
}
}
}
}
```
The 'space' post\_type meta is stored like this:
```
allSlots => array(
'timestamp' => '123456789', //timestamp representing this slot
'details' => array(
'slotStatus' => 'open', //this is either open or filled
'slotUser' => 123, //The ID of the user who owns the rental using this slot
'rentalID' => 345, //The post_id of the 'space_rental' that is using this slot
),
);
```
This 'space\_rental' post\_type meta is stored like this:
```
selectedSlots => array(
'spaceSlots' => array(
123456789, 654321987, 9876432654, etc...,// An array of timestamps in this rental
),
'spaceid' => 789, //The post_id of the 'space' where this rental is
);
```
|
There's a [**trash post**](https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post) hook
```
add_action( 'trash_post', 'my_func' );
function my_func( $postid ){
// We check if the global post type isn't ours and just return
global $post_type;
if ( $post_type != 'my_custom_post_type' ) return;
// My custom stuff for deleting my custom post type here
}
```
|
250,191 |
<p>I have written a plugin for my own site where I have an issue like "after user login to the site if he logout then again if he clicks on browser back button then the previous page showing again instead of login page". Iam trying the below code but it doesn't work.</p>
<pre><code><script>
window.onhashchange = function() {
<?php if( ! is_user_logged_in()) { $this->tewa_login(); } ?>
}
<script>
</code></pre>
<p>My logout code is below:</p>
<pre><code>if ( is_user_logged_in() ) {
$data .= '<li><a class="add-new" href="'. wp_logout_url() .'" class="btn btn-primary" >'.$this->icon_sign_out.' Logout</a></li>';
}
</code></pre>
<p>Can the below code works or not?</p>
<pre><code>function my_redirect(){
<script>
location.reload();
</script>
exit();
}
add_filter('wp_logout','my_redirect');
</code></pre>
<p>I think this issue totally browser issue not belongs to server. I think just a page refresh that does the trick. I was using 'wp_logout_url' for user logout. how to do it can anyone plz tell me? Thanks in advance.</p>
|
[
{
"answer_id": 250176,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>There's a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post\" rel=\"nofollow noreferrer\"><strong>trash post</strong></a> hook</p>\n\n<pre><code>add_action( 'trash_post', 'my_func' );\nfunction my_func( $postid ){\n\n // We check if the global post type isn't ours and just return\n global $post_type; \n if ( $post_type != 'my_custom_post_type' ) return;\n\n // My custom stuff for deleting my custom post type here\n}\n</code></pre>\n"
},
{
"answer_id": 250193,
"author": "sdx11",
"author_id": 106577,
"author_profile": "https://wordpress.stackexchange.com/users/106577",
"pm_score": 0,
"selected": false,
"text": "<p>if you want to to catch it when user delete( means click trash on post) \nthen possible solution is to use <strong>trash_post</strong> hook</p>\n\n<pre><code>add_action( 'trash_post', 'my_func_before_trash',999,1);\n\nfunction my_func_before_trash($postid){\n //my custom code\n}\n</code></pre>\n"
}
] |
2016/12/23
|
[
"https://wordpress.stackexchange.com/questions/250191",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106542/"
] |
I have written a plugin for my own site where I have an issue like "after user login to the site if he logout then again if he clicks on browser back button then the previous page showing again instead of login page". Iam trying the below code but it doesn't work.
```
<script>
window.onhashchange = function() {
<?php if( ! is_user_logged_in()) { $this->tewa_login(); } ?>
}
<script>
```
My logout code is below:
```
if ( is_user_logged_in() ) {
$data .= '<li><a class="add-new" href="'. wp_logout_url() .'" class="btn btn-primary" >'.$this->icon_sign_out.' Logout</a></li>';
}
```
Can the below code works or not?
```
function my_redirect(){
<script>
location.reload();
</script>
exit();
}
add_filter('wp_logout','my_redirect');
```
I think this issue totally browser issue not belongs to server. I think just a page refresh that does the trick. I was using 'wp\_logout\_url' for user logout. how to do it can anyone plz tell me? Thanks in advance.
|
There's a [**trash post**](https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post) hook
```
add_action( 'trash_post', 'my_func' );
function my_func( $postid ){
// We check if the global post type isn't ours and just return
global $post_type;
if ( $post_type != 'my_custom_post_type' ) return;
// My custom stuff for deleting my custom post type here
}
```
|
250,205 |
<p>I'm preparing plugin and I have trouble to call (and return) javascript from each (same) shortcode in one wp page/post. Javascript returns values only to last shortcode in page.</p>
<p>PHP code here:</p>
<pre><code>add_shortcode( 'ada_chart', 'ada_chart_stranka' );
function ada_chart_stranka ($atts) {
$a = shortcode_atts( array(
'cid' => '',
), $atts );
$cislo_chart = $a['cid'];
wp_register_script( 'ada_chart_handle', plugins_url().'/ada-chart/js/ada-chart1.js' );
$ada_sheet_params = array(
'ada_ch_cislo' => $cislo_chart,
);
wp_localize_script( 'ada_chart_handle', 'ada_ch', $ada_sheet_params );
wp_enqueue_script( 'ada_chart_handle');
return 'atribut: '.$cislo_chart;
}
</code></pre>
<p>and JS script here:</p>
<pre><code> var cisloChart = ada_ch.ada_ch_cislo;
document.getElementById('chart_div'+cisloChart).innerHTML = 'Cislo: ' + cisloChart;
</code></pre>
<p>Can anybody hepl me? Thanks</p>
|
[
{
"answer_id": 250176,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>There's a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post\" rel=\"nofollow noreferrer\"><strong>trash post</strong></a> hook</p>\n\n<pre><code>add_action( 'trash_post', 'my_func' );\nfunction my_func( $postid ){\n\n // We check if the global post type isn't ours and just return\n global $post_type; \n if ( $post_type != 'my_custom_post_type' ) return;\n\n // My custom stuff for deleting my custom post type here\n}\n</code></pre>\n"
},
{
"answer_id": 250193,
"author": "sdx11",
"author_id": 106577,
"author_profile": "https://wordpress.stackexchange.com/users/106577",
"pm_score": 0,
"selected": false,
"text": "<p>if you want to to catch it when user delete( means click trash on post) \nthen possible solution is to use <strong>trash_post</strong> hook</p>\n\n<pre><code>add_action( 'trash_post', 'my_func_before_trash',999,1);\n\nfunction my_func_before_trash($postid){\n //my custom code\n}\n</code></pre>\n"
}
] |
2016/12/23
|
[
"https://wordpress.stackexchange.com/questions/250205",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109514/"
] |
I'm preparing plugin and I have trouble to call (and return) javascript from each (same) shortcode in one wp page/post. Javascript returns values only to last shortcode in page.
PHP code here:
```
add_shortcode( 'ada_chart', 'ada_chart_stranka' );
function ada_chart_stranka ($atts) {
$a = shortcode_atts( array(
'cid' => '',
), $atts );
$cislo_chart = $a['cid'];
wp_register_script( 'ada_chart_handle', plugins_url().'/ada-chart/js/ada-chart1.js' );
$ada_sheet_params = array(
'ada_ch_cislo' => $cislo_chart,
);
wp_localize_script( 'ada_chart_handle', 'ada_ch', $ada_sheet_params );
wp_enqueue_script( 'ada_chart_handle');
return 'atribut: '.$cislo_chart;
}
```
and JS script here:
```
var cisloChart = ada_ch.ada_ch_cislo;
document.getElementById('chart_div'+cisloChart).innerHTML = 'Cislo: ' + cisloChart;
```
Can anybody hepl me? Thanks
|
There's a [**trash post**](https://codex.wordpress.org/Plugin_API/Action_Reference/trash_post) hook
```
add_action( 'trash_post', 'my_func' );
function my_func( $postid ){
// We check if the global post type isn't ours and just return
global $post_type;
if ( $post_type != 'my_custom_post_type' ) return;
// My custom stuff for deleting my custom post type here
}
```
|
250,210 |
<p>I'm using the customizer to upload an image. The code I have below displays the full size image ok but I would like to instead display a custom size of that image that I created below that. </p>
<p>This is the code in my template file:</p>
<pre><code><img src="<?php echo get_theme_mod( 'image-1' , get_template_directory_uri().'/images/default.jpg' ); ?>">
</code></pre>
<p>This is the code in my <code>functions.php</code> file to add the custom size:</p>
<pre><code>add_image_size( 'image-thumbnail', 525, 350, true );
</code></pre>
|
[
{
"answer_id": 250217,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Apparently, your mod is storing the complete path to the image as a string. That leaves you little alternative but to do a search and replace on the string:</p>\n\n<pre><code>$img = get_theme_mod('image-1');\nif (!empty ($img)) {\n $img = preg_replace ('.(jpg|jpeg|png|gif)$','-525x350$0');\n if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';\n }\n else if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';\n</code></pre>\n\n<p>In words. Get the mod. If it exists search <code>$img</code> for the occurence of <code>jpg|jpeg|png|gif</code> at the end of the string and then prepend it with the image size, eg <code>...image-525x350.jpg</code>. If that file does not exist, use the default. If there is no mod, also use the default.</p>\n"
},
{
"answer_id": 269310,
"author": "franklylately",
"author_id": 111023,
"author_profile": "https://wordpress.stackexchange.com/users/111023",
"pm_score": 0,
"selected": false,
"text": "<p>Working from cjbj's answer, you may need to add delimiters to have your preg_replace work correctly:</p>\n\n<pre><code>$img = get_theme_mod('image-1');\nif (!empty ($img)) {\n $img = preg_replace ('/.(jpg|jpeg|png|gif)$/','-525x350$0');\n if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';\n }\nelse if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';\n</code></pre>\n"
}
] |
2016/12/23
|
[
"https://wordpress.stackexchange.com/questions/250210",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40536/"
] |
I'm using the customizer to upload an image. The code I have below displays the full size image ok but I would like to instead display a custom size of that image that I created below that.
This is the code in my template file:
```
<img src="<?php echo get_theme_mod( 'image-1' , get_template_directory_uri().'/images/default.jpg' ); ?>">
```
This is the code in my `functions.php` file to add the custom size:
```
add_image_size( 'image-thumbnail', 525, 350, true );
```
|
Apparently, your mod is storing the complete path to the image as a string. That leaves you little alternative but to do a search and replace on the string:
```
$img = get_theme_mod('image-1');
if (!empty ($img)) {
$img = preg_replace ('.(jpg|jpeg|png|gif)$','-525x350$0');
if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
}
else if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
```
In words. Get the mod. If it exists search `$img` for the occurence of `jpg|jpeg|png|gif` at the end of the string and then prepend it with the image size, eg `...image-525x350.jpg`. If that file does not exist, use the default. If there is no mod, also use the default.
|
250,241 |
<p>My WordPress (v4.7) site's media settings only shows sizes for Thumbnail, Medium, and Large. How do I add a Small size to it?</p>
|
[
{
"answer_id": 250217,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Apparently, your mod is storing the complete path to the image as a string. That leaves you little alternative but to do a search and replace on the string:</p>\n\n<pre><code>$img = get_theme_mod('image-1');\nif (!empty ($img)) {\n $img = preg_replace ('.(jpg|jpeg|png|gif)$','-525x350$0');\n if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';\n }\n else if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';\n</code></pre>\n\n<p>In words. Get the mod. If it exists search <code>$img</code> for the occurence of <code>jpg|jpeg|png|gif</code> at the end of the string and then prepend it with the image size, eg <code>...image-525x350.jpg</code>. If that file does not exist, use the default. If there is no mod, also use the default.</p>\n"
},
{
"answer_id": 269310,
"author": "franklylately",
"author_id": 111023,
"author_profile": "https://wordpress.stackexchange.com/users/111023",
"pm_score": 0,
"selected": false,
"text": "<p>Working from cjbj's answer, you may need to add delimiters to have your preg_replace work correctly:</p>\n\n<pre><code>$img = get_theme_mod('image-1');\nif (!empty ($img)) {\n $img = preg_replace ('/.(jpg|jpeg|png|gif)$/','-525x350$0');\n if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';\n }\nelse if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';\n</code></pre>\n"
}
] |
2016/12/23
|
[
"https://wordpress.stackexchange.com/questions/250241",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51855/"
] |
My WordPress (v4.7) site's media settings only shows sizes for Thumbnail, Medium, and Large. How do I add a Small size to it?
|
Apparently, your mod is storing the complete path to the image as a string. That leaves you little alternative but to do a search and replace on the string:
```
$img = get_theme_mod('image-1');
if (!empty ($img)) {
$img = preg_replace ('.(jpg|jpeg|png|gif)$','-525x350$0');
if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
}
else if (!file_exists($img)) $img = get_template_directory_uri().'/images/default.jpg';
```
In words. Get the mod. If it exists search `$img` for the occurence of `jpg|jpeg|png|gif` at the end of the string and then prepend it with the image size, eg `...image-525x350.jpg`. If that file does not exist, use the default. If there is no mod, also use the default.
|
250,264 |
<p>Every WordPress page can be described as having two titles:</p>
<ol>
<li><p>The page/post title, which is displayed within the page/post via the <code>the_title()</code> function call</p></li>
<li><p>The html <code><title></title></code> tag that displays the title on top of the browser</p></li>
</ol>
<p>I am writing a plugin which at one point should change the title of a page dynamically (well, it should change both titles described above).</p>
<p>So, for step 1 above, I found multiple solutions on Stack Overflow (such as <a href="https://wordpress.stackexchange.com/questions/46707/change-page-title-from-plugin">this</a> or <a href="https://wordpress.stackexchange.com/questions/33101/how-do-i-set-the-page-title-dynamically">this</a>). Those are great for only step 1 above.</p>
<p>For step 2, I found <a href="https://wordpress.stackexchange.com/questions/51479/setting-title-using-wp-title-filter">this</a> solution; in a nutshell, this is how it works:</p>
<pre><code>add_filter('wp_title', 'change_page_title');
function change_page_title ($title) {
// Do some magic, and eventually modify $title then return it
return $title;
}
</code></pre>
<p>But the suggested solution is not working for me; and by not working I mean that the filter is not calling the associated function. I am not sure what the problem is; is it because this filter is being called from within the plugin not the theme? (Just FYI, I do not have access to the theme files, so it has to be done from within the plugin).</p>
<p>How can I accomplish this? How can I change the browser title of a page dynamically from within a plugin? </p>
<p>Thanks.</p>
|
[
{
"answer_id": 250266,
"author": "pankaj choudhary",
"author_id": 109569,
"author_profile": "https://wordpress.stackexchange.com/users/109569",
"pm_score": 1,
"selected": false,
"text": "<p>Using this code on you page.php or page which you want to change\n<code><pre>\n<title><?php wp_title(); ?> | <?php bloginfo(‘name’); ?></title>\n</pre></code></p>\n"
},
{
"answer_id": 250269,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 4,
"selected": true,
"text": "<p>A post or page has only one title, the title tag <code><title></code> is the document title.</p>\n\n<p>The filter <code>wp_title</code> filters the output of <code>wp_title()</code> function, which was used before to output the title of the document. In WordPress 4.1, the title-tag support in themes was introduced and <a href=\"https://developer.wordpress.org/reference/functions/wp_get_document_title/\" rel=\"noreferrer\"><code>wp_get_document_title()</code></a> is used instead of <code>wp_title()</code>. So, if your theme supports <code>title-tag</code>, <code>wp_title</code> filter has not effect, but you can use a other filters:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/pre_get_document_title/\" rel=\"noreferrer\"><code>pre_get_document_title</code></a> to set a new title</p>\n\n<pre><code>add_filter( 'pre_get_document_title', 'cyb_change_page_title' );\nfunction cyb_change_page_title () {\n\n return \"Custom title\";\n\n}\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/document_title_separator/\" rel=\"noreferrer\"><code>document_title_separator</code></a> to filter the title separator</p>\n\n<pre><code>add_filter('document_title_separator', 'cyb_change_document_title_separator');\nfunction cyb_change_document_title_separator ( $sep ) {\n\n return \"|\";\n\n}\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/document_title_parts/\" rel=\"noreferrer\"><code>documente_title_parts</code></a> to filter different parts of the title: title, page number, tagline and site name.</p>\n\n<pre><code>add_filter( 'document_title_parts', 'cyb_change_document_title_parts' );\nfunction cyb_change_document_title_parts ( $title_parts ) {\n\n $title_parts['title'] = 'Custom title';\n $title_parts['page'] = 54;\n $title_parts['tagline'] = \"Custom tagline\";\n $title_parts['site'] = \"My Site\"; // When not on home page\n\n return $title_parts;\n\n}\n</code></pre>\n\n<p>PD: You can use <a href=\"https://developer.wordpress.org/reference/functions/current_theme_supports/\" rel=\"noreferrer\"><code>current_theme_supports( 'title-tag' )</code></a> to check if theme supports <code>title-tag</code> or not.</p>\n"
}
] |
2016/12/24
|
[
"https://wordpress.stackexchange.com/questions/250264",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34253/"
] |
Every WordPress page can be described as having two titles:
1. The page/post title, which is displayed within the page/post via the `the_title()` function call
2. The html `<title></title>` tag that displays the title on top of the browser
I am writing a plugin which at one point should change the title of a page dynamically (well, it should change both titles described above).
So, for step 1 above, I found multiple solutions on Stack Overflow (such as [this](https://wordpress.stackexchange.com/questions/46707/change-page-title-from-plugin) or [this](https://wordpress.stackexchange.com/questions/33101/how-do-i-set-the-page-title-dynamically)). Those are great for only step 1 above.
For step 2, I found [this](https://wordpress.stackexchange.com/questions/51479/setting-title-using-wp-title-filter) solution; in a nutshell, this is how it works:
```
add_filter('wp_title', 'change_page_title');
function change_page_title ($title) {
// Do some magic, and eventually modify $title then return it
return $title;
}
```
But the suggested solution is not working for me; and by not working I mean that the filter is not calling the associated function. I am not sure what the problem is; is it because this filter is being called from within the plugin not the theme? (Just FYI, I do not have access to the theme files, so it has to be done from within the plugin).
How can I accomplish this? How can I change the browser title of a page dynamically from within a plugin?
Thanks.
|
A post or page has only one title, the title tag `<title>` is the document title.
The filter `wp_title` filters the output of `wp_title()` function, which was used before to output the title of the document. In WordPress 4.1, the title-tag support in themes was introduced and [`wp_get_document_title()`](https://developer.wordpress.org/reference/functions/wp_get_document_title/) is used instead of `wp_title()`. So, if your theme supports `title-tag`, `wp_title` filter has not effect, but you can use a other filters:
[`pre_get_document_title`](https://developer.wordpress.org/reference/hooks/pre_get_document_title/) to set a new title
```
add_filter( 'pre_get_document_title', 'cyb_change_page_title' );
function cyb_change_page_title () {
return "Custom title";
}
```
[`document_title_separator`](https://developer.wordpress.org/reference/hooks/document_title_separator/) to filter the title separator
```
add_filter('document_title_separator', 'cyb_change_document_title_separator');
function cyb_change_document_title_separator ( $sep ) {
return "|";
}
```
[`documente_title_parts`](https://developer.wordpress.org/reference/hooks/document_title_parts/) to filter different parts of the title: title, page number, tagline and site name.
```
add_filter( 'document_title_parts', 'cyb_change_document_title_parts' );
function cyb_change_document_title_parts ( $title_parts ) {
$title_parts['title'] = 'Custom title';
$title_parts['page'] = 54;
$title_parts['tagline'] = "Custom tagline";
$title_parts['site'] = "My Site"; // When not on home page
return $title_parts;
}
```
PD: You can use [`current_theme_supports( 'title-tag' )`](https://developer.wordpress.org/reference/functions/current_theme_supports/) to check if theme supports `title-tag` or not.
|
250,280 |
<p>Considering regular WordPress ajax requests like these:</p>
<pre><code>add_action( 'wp_ajax_merrychristmas_happynewyear', array( $this, 'merrychristmas_happynewyear' ) );
add_action( 'wp_ajax_nopriv_merrychristmas_happynewyear', array( $this, 'merrychristmas_happynewyear' ) );
</code></pre>
<p>Will it be best to end function <code>merrychristmas_happynewyear</code> with <code>die()</code>, <code>die(0)</code>, <code>wp_die()</code>, or something else and why?</p>
|
[
{
"answer_id": 250282,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 4,
"selected": false,
"text": "<p>From the codex <a href=\"https://codex.wordpress.org/AJAX_in_Plugins\"><strong>AJAX in Plugins</strong></a></p>\n\n<pre><code>add_action( 'wp_ajax_my_action', 'my_action_callback' );\n\nfunction my_action_callback() {\n global $wpdb; // this is how you get access to the database\n\n $whatever = intval( $_POST['whatever'] );\n\n $whatever += 10;\n\n echo $whatever;\n\n wp_die(); // this is required to terminate immediately and return a proper response\n}\n</code></pre>\n\n<blockquote>\n <p>Notice the use of <code>wp_die()</code>, instead of <code>die()</code> or <code>exit()</code>. Most of the\n time you should be using <code>wp_die()</code> in your Ajax callback function. This\n provides better integration with WordPress and makes it easier to test\n your code.</p>\n</blockquote>\n"
},
{
"answer_id": 250331,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 3,
"selected": false,
"text": "<p>You can also use <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json\"><code>wp_send_json()</code></a> described in the Codex as <code>send a JSON response back to an AJAX request, and die().</code></p>\n\n<p>So, if you have to return an array, you only have end your function with <code>wp_send_json($array_with_values);</code>. No need to <code>echo</code> or <code>die</code>.</p>\n\n<p>You also get two help helper functions <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json_success\"><code>wp_send_json_success()</code></a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json_error\"><code>wp_send_json_error()</code></a> which adds a key named <code>success</code> which will be <code>true</code> or <code>false</code> respectively.</p>\n\n<p>For example:</p>\n\n<pre><code>$array_val = range( 1,10 );\nvar_dump( wp_send_json_error( $array_val ) ); # Output: {\"success\":false,\"data\":[1,2,3,4,5,6,7,8,9,10]}\necho 'Hey there'; # Not executed because already died.\n</code></pre>\n"
},
{
"answer_id": 255059,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>This is just in addition to what others said. The reason to prefer <code>wp_die</code> is that core can trigger actions there and plugins can properly complete things like tracing, monitoring, or caching. </p>\n\n<p>In general you should always prefer a core API call over if one available as it is most likely adding some value (caching, plugin integration or whatever) which you don't get from the direct PHP call.</p>\n"
},
{
"answer_id": 255199,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 6,
"selected": true,
"text": "<p>Using <code>wp_die()</code> is the best of those options.</p>\n\n<p>As others have noted, there are many reasons to prefer a WordPress-specific function over the plain <code>die</code> or <code>exit</code>:</p>\n\n<ul>\n<li>It allows other plugins to hook into the actions called by <code>wp_die()</code>.</li>\n<li>It allows a special handler for exiting to be used based on context (the behavior of <code>wp_die()</code> is tailored based on whether the request is an Ajax request or not).</li>\n<li>It makes it possible to test your code.</li>\n</ul>\n\n<p>The last one is more important, which is why <a href=\"https://codex.wordpress.org/index.php?title=AJAX_in_Plugins&diff=148870&oldid=148219\" rel=\"noreferrer\">I added that note to the Codex</a>. If you want to <a href=\"http://codesymphony.co/wp-ajax-plugin-unit-testing/\" rel=\"noreferrer\">create unit/integration tests</a> for your code, you will not be able to test a function that calls <code>exit</code> or <code>die</code> directly. It will terminate the script, like it is supposed to. The way that WordPress's own tests are set up to avoid this (for the Ajax callbacks that it has tests for), is to hook into the actions triggered by <code>wp_die()</code> and throw an exception. This allows the exception to be caught within the test, and the output of the callback (if any) to be analyzed.</p>\n\n<p>The only time that you would use <code>die</code> or <code>exit</code> is if you want to bypass any special handling from <code>wp_die()</code> and kill the execution immediately. There are some places where WordPress does this (and other places where it might use <code>die</code> directly just because the handling from <code>wp_die()</code> is not important, or nobody has attempted to create tests for a piece of code yet, so it was overlooked). Remember that this also makes your code more difficult to test, so it would generally only be used in code that isn't in a function body anyway (like WordPress does in <code>admin-ajax.php</code>). So if the handling from <code>wp_die()</code> is specifically not desired, or you are killing the script at a certain point as a precaution (like <code>admin-ajax.php</code> does, expecting that usually an Ajax callback will have already properly exited), then you might consider using <code>die</code> directly.</p>\n\n<p>In terms of <code>wp_die()</code> vs <code>wp_die( 0 )</code>, which you should use depends on what is handling the response of that Ajax request on the front end. If it is expecting a particular response body, then you need to pass that message (or integer, in this case) to <code>wp_die()</code>. If all it is listening for is the response being successful (<code>200</code> response code or whatever), then there is no need to pass anything to <code>wp_die()</code>. I would note, though, that ending with <code>wp_die( 0 )</code> would make the response indistinguishable from the default <code>admin-ajax.php</code> response. So ending with <code>0</code> does not tell you whether your callback was hooked up properly and actually ran. A different message would be better.</p>\n\n<p>As pointed out in other answers, you will often find <code>wp_send_json()</code> et al. to be helpful if you are sending a JSON response back, which is generally a good idea. This is also superior to just calling <code>wp_die()</code> with a code, because you can pass much more information back in a JSON object, if needed. Using <code>wp_send_json_success()</code> and <code>wp_send_json_error()</code> will also send the success/error message back in a standard format that any JS Ajax helper functions provided by WordPress will be able to understand (like <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-includes/js/wp-util.js?rev=37851#L99\" rel=\"noreferrer\"><code>wp.ajax</code></a>).</p>\n\n<p><strong>TL;DR:</strong> You should probably always use <code>wp_die()</code>, whether in an Ajax callback or not. Even better, send information back with <code>wp_send_json()</code> and friends. </p>\n"
},
{
"answer_id": 255200,
"author": "Greeso",
"author_id": 34253,
"author_profile": "https://wordpress.stackexchange.com/users/34253",
"pm_score": 1,
"selected": false,
"text": "<p>Use <code>wp_die()</code>. It is better to use WordPress functions as much as you can.</p>\n"
},
{
"answer_id": 255334,
"author": "Saran",
"author_id": 25868,
"author_profile": "https://wordpress.stackexchange.com/users/25868",
"pm_score": 2,
"selected": false,
"text": "<p>For using wordpress ajax / woo commerce ajax general syntax is as follows:</p>\n\n<pre><code>add_action( 'wp_ajax_my_action', 'my_action_callback' );\nadd_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );\nfunction my_action_callback()\n{\n// your code goes here\n\nwp_die();\n\n}\n</code></pre>\n\n<p>You should use wp_die() at end of the function.Because wordpress internally uses a <strong>filter</strong> during wp_die() function.So any plugin which is working using that filter may not work if we do not include the wp_die(). Also die() and other functions are immediately kill the PHP execution without considering any wordpress function which should be consider while terminating execution.</p>\n\n<p>If you are using wp_send_json() inside you function like this</p>\n\n<pre><code> function my_action_callback()\n {\n // your code goes here\n\n wp_send_json();\n\n //wp_die(); not necessary to use wp_die();\n\n }\n</code></pre>\n\n<p><strong>Its not necessary to use wp_die() at the end if you include wp_send_json() inside callback function</strong>. because wordpress itself use wp_die() function safely inside wp_send_json() function.</p>\n"
},
{
"answer_id": 255523,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": false,
"text": "<p>I will not accept this answer, this would not be fair. I just wanted to create an outline and possible hints on the items I find important:</p>\n\n<h3>The main definition of wp-die()</h3>\n\n<pre><code>File: wp-includes/functions.php\n2607: /**\n2608: * Kill WordPress execution and display HTML message with error message.\n2609: *\n2610: * This function complements the `die()` PHP function. The difference is that\n2611: * HTML will be displayed to the user. It is recommended to use this function\n2612: * only when the execution should not continue any further. It is not recommended\n2613: * to call this function very often, and try to handle as many errors as possible\n2614: * silently or more gracefully.\n2615: *\n2616: * As a shorthand, the desired HTTP response code may be passed as an integer to\n2617: * the `$title` parameter (the default title would apply) or the `$args` parameter.\n2618: *\n2619: * @since 2.0.4\n2620: * @since 4.1.0 The `$title` and `$args` parameters were changed to optionally accept\n2621: * an integer to be used as the response code.\n2622: *\n2623: * @param string|WP_Error $message Optional. Error message. If this is a WP_Error object,\n2624: * and not an Ajax or XML-RPC request, the error's messages are used.\n2625: * Default empty.\n2626: * @param string|int $title Optional. Error title. If `$message` is a `WP_Error` object,\n2627: * error data with the key 'title' may be used to specify the title.\n2628: * If `$title` is an integer, then it is treated as the response\n2629: * code. Default empty.\n2630: * @param string|array|int $args {\n2631: * Optional. Arguments to control behavior. If `$args` is an integer, then it is treated\n2632: * as the response code. Default empty array.\n2633: *\n2634: * @type int $response The HTTP response code. Default 200 for Ajax requests, 500 otherwise.\n2635: * @type bool $back_link Whether to include a link to go back. Default false.\n2636: * @type string $text_direction The text direction. This is only useful internally, when WordPress\n2637: * is still loading and the site's locale is not set up yet. Accepts 'rtl'.\n2638: * Default is the value of is_rtl().\n2639: * }\n2640: */\n2641: function wp_die( $message = '', $title = '', $args = array() ) {\n2642: \n2643: if ( is_int( $args ) ) {\n2644: $args = array( 'response' => $args );\n2645: } elseif ( is_int( $title ) ) {\n2646: $args = array( 'response' => $title );\n2647: $title = '';\n2648: }\n2649: \n2650: if ( wp_doing_ajax() ) {\n2651: /**\n2652: * Filters the callback for killing WordPress execution for Ajax requests.\n2653: *\n2654: * @since 3.4.0\n2655: *\n2656: * @param callable $function Callback function name.\n2657: */\n2658: $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );\n2659: } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {\n2660: /**\n2661: * Filters the callback for killing WordPress execution for XML-RPC requests.\n2662: *\n2663: * @since 3.4.0\n2664: *\n2665: * @param callable $function Callback function name.\n2666: */\n2667: $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );\n2668: } else {\n2669: /**\n2670: * Filters the callback for killing WordPress execution for all non-Ajax, non-XML-RPC requests.\n2671: *\n2672: * @since 3.0.0\n2673: *\n2674: * @param callable $function Callback function name.\n2675: */\n2676: $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );\n2677: }\n2678: \n2679: call_user_func( $function, $message, $title, $args );\n2680: }\n</code></pre>\n\n<h3>wp_send_json</h3>\n\n<pre><code>File: wp-includes/functions.php\n3144: /**\n3145: * Send a JSON response back to an Ajax request.\n3146: *\n3147: * @since 3.5.0\n3148: * @since 4.7.0 The `$status_code` parameter was added.\n3149: *\n3150: * @param mixed $response Variable (usually an array or object) to encode as JSON,\n3151: * then print and die.\n3152: * @param int $status_code The HTTP status code to output.\n3153: */\n3154: function wp_send_json( $response, $status_code = null ) {\n3155: @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );\n3156: if ( null !== $status_code ) {\n3157: status_header( $status_code );\n3158: }\n3159: echo wp_json_encode( $response );\n3160: \n3161: if ( wp_doing_ajax() ) {\n3162: wp_die( '', '', array(\n3163: 'response' => null,\n3164: ) );\n3165: } else {\n3166: die;\n3167: }\n3168: }\n</code></pre>\n\n<h3>wp_doing_ajax</h3>\n\n<pre><code>File: wp-includes/load.php\n1044: /**\n1045: * Determines whether the current request is a WordPress Ajax request.\n1046: *\n1047: * @since 4.7.0\n1048: *\n1049: * @return bool True if it's a WordPress Ajax request, false otherwise.\n1050: */\n1051: function wp_doing_ajax() {\n1052: /**\n1053: * Filters whether the current request is a WordPress Ajax request.\n1054: *\n1055: * @since 4.7.0\n1056: *\n1057: * @param bool $wp_doing_ajax Whether the current request is a WordPress Ajax request.\n1058: */\n1059: return apply_filters( 'wp_doing_ajax', defined( 'DOING_AJAX' ) && DOING_AJAX );\n1060: }\n</code></pre>\n\n<hr>\n\n<p>Typically what we get from ajax call is some kind of the response.\nThe response may be encoded in json or may not be encoded in json.</p>\n\n<p>In case we need <code>json</code> outupt <code>wp_send_json</code> or two satelites are great idea.</p>\n\n<p>However, we may return <code>x-www-form-urlencoded</code> or <code>multipart/form-data</code> or <code>text/xml</code> or any other encoding type. In that case we don't use <code>wp_send_json</code>.</p>\n\n<p>We may return the whole html and in that case it has sense to use <code>wp_die()</code> first and second parameter, else these parameters should be empty.</p>\n\n<pre><code> wp_die( '', '', array(\n 'response' => null,\n ) );\n</code></pre>\n\n<p>But what is a benefit of calling <code>wp_die()</code> without parameters?</p>\n\n<hr>\n\n<p>Finaly, if you check the great WP core you may find </p>\n\n<pre><code>File: wp-includes/class-wp-ajax-response.php\n139: /**\n140: * Display XML formatted responses.\n141: *\n142: * Sets the content type header to text/xml.\n143: *\n144: * @since 2.1.0\n145: */\n146: public function send() {\n147: header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ) );\n148: echo \"<?xml version='1.0' encoding='\" . get_option( 'blog_charset' ) . \"' standalone='yes'?><wp_ajax>\";\n149: foreach ( (array) $this->responses as $response )\n150: echo $response;\n151: echo '</wp_ajax>';\n152: if ( wp_doing_ajax() )\n153: wp_die();\n154: else\n155: die();\n</code></pre>\n\n<p>Both formats are used <code>die()</code> and <code>wp_die()</code>. Can you explain why?</p>\n\n<p>Finally here is what <code>admin-ajax.php</code> returns <code>die( '0' );</code></p>\n\n<p>Why not <code>wp_die(...)</code>? </p>\n"
},
{
"answer_id": 255822,
"author": "Faisal Alvi",
"author_id": 73262,
"author_profile": "https://wordpress.stackexchange.com/users/73262",
"pm_score": 1,
"selected": false,
"text": "<p>If you use <code>echo</code>, it will force you to use <code>die()</code> or <code>die(0)</code> or <code>wp_die()</code>.</p>\n\n<p>If you don’t use <code>echo</code>, JavaScript can handle that. </p>\n\n<p>Then you should use a better way to return data: <code>wp_send_json()</code>.</p>\n\n<p>To send data in your callback (in <code>json</code> format), you can use followings:</p>\n\n<p><code>wp_send_json()</code></p>\n\n<p><code>wp_send_json_success()</code></p>\n\n<p><code>wp_send_json_error()</code></p>\n\n<p>All of them will die for you. No need to exit or die afterwards.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>And if you don't need <code>json</code> as output format, you should use:</p>\n\n<p><code>wp_die($response)</code></p>\n\n<p>It will return your response before it dies. As per the codex:</p>\n\n<blockquote>\n <p>The function <code>wp_die()</code> is designed to give output just before it dies\n to avoid empty or time-outing responses.</p>\n</blockquote>\n\n<p>Please read full codex article <a href=\"https://codex.wordpress.org/Function_Reference/wp_die\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
] |
2016/12/24
|
[
"https://wordpress.stackexchange.com/questions/250280",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88606/"
] |
Considering regular WordPress ajax requests like these:
```
add_action( 'wp_ajax_merrychristmas_happynewyear', array( $this, 'merrychristmas_happynewyear' ) );
add_action( 'wp_ajax_nopriv_merrychristmas_happynewyear', array( $this, 'merrychristmas_happynewyear' ) );
```
Will it be best to end function `merrychristmas_happynewyear` with `die()`, `die(0)`, `wp_die()`, or something else and why?
|
Using `wp_die()` is the best of those options.
As others have noted, there are many reasons to prefer a WordPress-specific function over the plain `die` or `exit`:
* It allows other plugins to hook into the actions called by `wp_die()`.
* It allows a special handler for exiting to be used based on context (the behavior of `wp_die()` is tailored based on whether the request is an Ajax request or not).
* It makes it possible to test your code.
The last one is more important, which is why [I added that note to the Codex](https://codex.wordpress.org/index.php?title=AJAX_in_Plugins&diff=148870&oldid=148219). If you want to [create unit/integration tests](http://codesymphony.co/wp-ajax-plugin-unit-testing/) for your code, you will not be able to test a function that calls `exit` or `die` directly. It will terminate the script, like it is supposed to. The way that WordPress's own tests are set up to avoid this (for the Ajax callbacks that it has tests for), is to hook into the actions triggered by `wp_die()` and throw an exception. This allows the exception to be caught within the test, and the output of the callback (if any) to be analyzed.
The only time that you would use `die` or `exit` is if you want to bypass any special handling from `wp_die()` and kill the execution immediately. There are some places where WordPress does this (and other places where it might use `die` directly just because the handling from `wp_die()` is not important, or nobody has attempted to create tests for a piece of code yet, so it was overlooked). Remember that this also makes your code more difficult to test, so it would generally only be used in code that isn't in a function body anyway (like WordPress does in `admin-ajax.php`). So if the handling from `wp_die()` is specifically not desired, or you are killing the script at a certain point as a precaution (like `admin-ajax.php` does, expecting that usually an Ajax callback will have already properly exited), then you might consider using `die` directly.
In terms of `wp_die()` vs `wp_die( 0 )`, which you should use depends on what is handling the response of that Ajax request on the front end. If it is expecting a particular response body, then you need to pass that message (or integer, in this case) to `wp_die()`. If all it is listening for is the response being successful (`200` response code or whatever), then there is no need to pass anything to `wp_die()`. I would note, though, that ending with `wp_die( 0 )` would make the response indistinguishable from the default `admin-ajax.php` response. So ending with `0` does not tell you whether your callback was hooked up properly and actually ran. A different message would be better.
As pointed out in other answers, you will often find `wp_send_json()` et al. to be helpful if you are sending a JSON response back, which is generally a good idea. This is also superior to just calling `wp_die()` with a code, because you can pass much more information back in a JSON object, if needed. Using `wp_send_json_success()` and `wp_send_json_error()` will also send the success/error message back in a standard format that any JS Ajax helper functions provided by WordPress will be able to understand (like [`wp.ajax`](https://core.trac.wordpress.org/browser/trunk/src/wp-includes/js/wp-util.js?rev=37851#L99)).
**TL;DR:** You should probably always use `wp_die()`, whether in an Ajax callback or not. Even better, send information back with `wp_send_json()` and friends.
|
250,288 |
<p>can anyone help me </p>
<pre><code>define('FTP_PUBKEY','/home/use/.ssh/id_rsa');
define('FTP_PRIKEY','/home/user/.ssh/id_rsa');
define('FTP_USER','');
define('FTP_PASS','');
define('FTP_HOST','127.0.0.1:22');
</code></pre>
<p>install at located <code>home/user/wordpress</code></p>
<p>keys located at </p>
<p>getting incorrect keys</p>
<p>keys permissons 600, 600 folfer 755</p>
|
[
{
"answer_id": 250320,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 2,
"selected": false,
"text": "<p>For connection through ssh, you have to specify the ssh user using <code>FTP_USER</code></p>\n\n<pre><code>define( 'FS_METHOD', 'ssh' );\ndefine( 'FTP_BASE', '/home/user/wordpress' );\ndefine( 'FTP_PUBKEY', '/home/user/.ssh/id_rsa.pub' );\ndefine( 'FTP_PRIKEY', '/home/user/.ssh/id_rsa' );\ndefine( 'FTP_USER', 'user' );\ndefine( 'FTP_HOST', 'localhost:22' );\n</code></pre>\n\n<p>I think you also need to define <code>FTP_BASE</code>.</p>\n\n<p>You also need to enable ssh upgrade access. From the Codex:</p>\n\n<h2>Enabling SSH Upgrade Access</h2>\n\n<p><strong>There are two ways to upgrade using SSH2.</strong></p>\n\n<p>The first is to use the <a href=\"http://wordpress.org/plugins/ssh-sftp-updater-support/\" rel=\"nofollow noreferrer\">SSH SFTP Updater Support plugin</a>. The second is to use the built-in SSH2 upgrader, which requires the pecl SSH2 extension be installed.</p>\n\n<p>To install the pecl SSH2 extension you will need to issue a command similar to the following or talk to your web hosting provider to get this installed:</p>\n\n<pre><code>pecl install ssh2\n</code></pre>\n\n<p>After installing the pecl ssh2 extension you will need to modify your php configuration to automatically load this extension.</p>\n\n<p>pecl is provided by the pear package in most linux distributions. To install pecl in Redhat/Fedora/CentOS:</p>\n\n<pre><code>yum -y install php-pear\n</code></pre>\n\n<p>To install pecl in Debian/Ubuntu:</p>\n\n<pre><code>apt-get install php-pear\n</code></pre>\n\n<p>It is recommended to use a private key that is not pass-phrase protected. There have been numerous reports that pass phrase protected private keys do not work properly. If you decide to try a pass phrase protected private key you will need to enter the pass phrase for the private key as FTP_PASS, or entering it in the \"Password\" field in the presented credential field when installing updates.</p>\n"
},
{
"answer_id": 295748,
"author": "theonlineking.com",
"author_id": 109580,
"author_profile": "https://wordpress.stackexchange.com/users/109580",
"pm_score": 1,
"selected": false,
"text": "<p>I asked this question when i am newbie. But finally realized no need to setup ssh and sftp even ftp account for wordpres when you are using in vps or cloud.</p>\n\n<p>I have used sftp client to file transfer. But some plugins installation not worked due to ownership problems. I have changed permission to Apache user and group www-data .</p>\n"
}
] |
2016/12/24
|
[
"https://wordpress.stackexchange.com/questions/250288",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109580/"
] |
can anyone help me
```
define('FTP_PUBKEY','/home/use/.ssh/id_rsa');
define('FTP_PRIKEY','/home/user/.ssh/id_rsa');
define('FTP_USER','');
define('FTP_PASS','');
define('FTP_HOST','127.0.0.1:22');
```
install at located `home/user/wordpress`
keys located at
getting incorrect keys
keys permissons 600, 600 folfer 755
|
For connection through ssh, you have to specify the ssh user using `FTP_USER`
```
define( 'FS_METHOD', 'ssh' );
define( 'FTP_BASE', '/home/user/wordpress' );
define( 'FTP_PUBKEY', '/home/user/.ssh/id_rsa.pub' );
define( 'FTP_PRIKEY', '/home/user/.ssh/id_rsa' );
define( 'FTP_USER', 'user' );
define( 'FTP_HOST', 'localhost:22' );
```
I think you also need to define `FTP_BASE`.
You also need to enable ssh upgrade access. From the Codex:
Enabling SSH Upgrade Access
---------------------------
**There are two ways to upgrade using SSH2.**
The first is to use the [SSH SFTP Updater Support plugin](http://wordpress.org/plugins/ssh-sftp-updater-support/). The second is to use the built-in SSH2 upgrader, which requires the pecl SSH2 extension be installed.
To install the pecl SSH2 extension you will need to issue a command similar to the following or talk to your web hosting provider to get this installed:
```
pecl install ssh2
```
After installing the pecl ssh2 extension you will need to modify your php configuration to automatically load this extension.
pecl is provided by the pear package in most linux distributions. To install pecl in Redhat/Fedora/CentOS:
```
yum -y install php-pear
```
To install pecl in Debian/Ubuntu:
```
apt-get install php-pear
```
It is recommended to use a private key that is not pass-phrase protected. There have been numerous reports that pass phrase protected private keys do not work properly. If you decide to try a pass phrase protected private key you will need to enter the pass phrase for the private key as FTP\_PASS, or entering it in the "Password" field in the presented credential field when installing updates.
|
250,304 |
<p>Should <code>get_template_directory_uri()</code> be escaped using <code>esc_url()</code>?</p>
<p>I ask because taking an example from the default theme Twenty Fifteen the same function is used in two different places but only in one is it escaped.</p>
<pre><code>wp_enqueue_style( 'twentyfifteen-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentyfifteen-style' ), '20141010' );
</code></pre>
<p>-</p>
<pre><code><script src="<?php echo esc_url( get_template_directory_uri() ); ?>/js/html5.js"></script>
</code></pre>
<p>I would say that that <code>get_template_directory_uri()</code> does not need to be generated as the URL cannot be manipulated externally.</p>
|
[
{
"answer_id": 250311,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 4,
"selected": true,
"text": "<p>In that function we find a hook:</p>\n\n<pre><code>return apply_filters( \n 'template_directory_uri', \n $template_dir_uri, \n $template, \n $theme_root_uri\n);\n</code></pre>\n\n<p>So, yes, the URI can be changed by plugins, and you should escape its returned value. </p>\n\n<p>The same principle applies to all WordPress URI functions, like <code>get_home_url()</code>, <code>get_site_url()</code> and so on. Keep in mind that there are not only good plugin developers out there. Some make mistakes, maybe just very small ones that happen only in some circumstances.</p>\n\n<p>In case of <code>wp_enqueue_style()</code>, WordPress <strong>does</strong> escape the URL by default. But that is a wrapper for the <strong>global</strong> <code>WP_Styles</code> instance, and this in turn <a href=\"https://wordpress.stackexchange.com/a/108364/73\">can be replaced easily</a> – even with a less safe version. That's not very likely, but you should be aware of this possibility.</p>\n\n<p>Unfortunately, WP itself doesn't follow the <em>better safe than sorry</em> directive. It doesn't even escape translations. My advice is not to look at the core themes for best practices. Always look at the source of the data and see if it can be compromised.</p>\n"
},
{
"answer_id": 250697,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Here is our function in question.</p>\n<pre><code>File: wp-includes/theme.php\n320: /**\n321: * Retrieve theme directory URI.\n322: *\n323: * @since 1.5.0\n324: *\n325: * @return string Template directory URI.\n326: */\n327: function get_template_directory_uri() {\n328: $template = str_replace( '%2F', '/', rawurlencode( get_template() ) );\n329: $theme_root_uri = get_theme_root_uri( $template );\n330: $template_dir_uri = "$theme_root_uri/$template";\n331: \n332: /**\n333: * Filters the current theme directory URI.\n334: *\n335: * @since 1.5.0\n336: *\n337: * @param string $template_dir_uri The URI of the current theme directory.\n338: * @param string $template Directory name of the current theme.\n339: * @param string $theme_root_uri The themes root URI.\n340: */\n341: return apply_filters( 'template_directory_uri', $template_dir_uri, $template, $theme_root_uri );\n342: }\n343: \n</code></pre>\n<p>You write something like this in your plugin:</p>\n<pre><code>add_filter('template_directory_uri',function(){ return 'http://badserver.com/'; });\n</code></pre>\n<p>And you will have something like this on a website:</p>\n<p><a href=\"https://i.stack.imgur.com/s57nr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/s57nr.png\" alt=\"enter image description here\" /></a></p>\n<p>Bright is the future because I see a <code>WP_Theme</code> class doesn't implement the filter in the <code>WP_Theme::get_template_directory_uri()</code> method. We know slowly WordPress is getting better and better and more encapsulated.</p>\n<pre><code>File: wp-includes/class-wp-theme.php\n898: /**\n899: * Returns the URL to the directory of a theme's "template" files.\n900: *\n901: * In the case of a child theme, this is the URL to the directory of the\n902: * parent theme's files.\n903: *\n904: * @since 3.4.0\n905: * @access public\n906: *\n907: * @return string URL to the template directory.\n908: */\n909: public function get_template_directory_uri() {\n910: if ( $this->parent() )\n911: $theme_root_uri = $this->parent()->get_theme_root_uri();\n912: else\n913: $theme_root_uri = $this->get_theme_root_uri();\n914: \n915: return $theme_root_uri . '/' . str_replace( '%2F', '/', rawurlencode( $this->template ) );\n916: }\n</code></pre>\n<hr />\n<h3>More notes</h3>\n<p>You see someone defines in the theme someting like this:</p>\n<blockquote>\n<p><code>define( 'TEMPL_URI', get_template_directory_uri() );</code></p>\n</blockquote>\n<p>They say it is because they would like to make <code>'TEMPL_URI'</code> unfilterable. They are wrong. If a plugin set a bad filter this will happen before the theme, so the <code>'TEMPL_URI'</code> will be dirty.</p>\n<p>However, it is OK to define the constants, I just wanted to say the constant will not protect you.</p>\n<hr />\n<p>Another thing I found in <code>Twenty Seventeen</code>. In there I saw <code>get_theme_file_uri</code> function ( @since 4.7 )</p>\n<pre><code>File: wp-includes/link-template.php\n4026: /**\n4027: * Retrieves the URL of a file in the theme.\n4028: *\n4029: * Searches in the stylesheet directory before the template directory so themes\n4030: * which inherit from a parent theme can just override one file.\n4031: *\n4032: * @since 4.7.0\n4033: *\n4034: * @param string $file Optional. File to search for in the stylesheet directory.\n4035: * @return string The URL of the file.\n4036: */\n4037: function get_theme_file_uri( $file = '' ) {\n4038: $file = ltrim( $file, '/' );\n4039: \n4040: if ( empty( $file ) ) {\n4041: $url = get_stylesheet_directory_uri();\n4042: } elseif ( file_exists( get_stylesheet_directory() . '/' . $file ) ) {\n4043: $url = get_stylesheet_directory_uri() . '/' . $file;\n4044: } else {\n4045: $url = get_template_directory_uri() . '/' . $file;\n4046: }\n4047: \n4048: /**\n4049: * Filters the URL to a file in the theme.\n4050: *\n4051: * @since 4.7.0\n4052: *\n4053: * @param string $url The file URL.\n4054: * @param string $file The requested file to search for.\n4055: */\n4056: return apply_filters( 'theme_file_uri', $url, $file );\n4057: }\n</code></pre>\n<p>Again this filter <code>theme_file_uri</code> may impose a security problem like @toscho explained for <code>get_template_directory_uri</code>.</p>\n<h3>Conclusion</h3>\n<p>When the security is in question we need to be very careful. The problem in here is deeper than just escaping the single URL. It considers the whole <strong>WordPress plugins security model</strong>.</p>\n<p>Plugins do not need <code>get_template_directory_uri()</code> function and the filter in there to do the bad things. They can execute with the same privileges as the WordPress core — they can do anything.</p>\n<p>Malicious JavaScript that bad plugins may inject may read your passwords while you type.</p>\n"
},
{
"answer_id": 250782,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Will try to make swissspidy's comment into an answer. Short version - it depends.</p>\n\n<p>Escaping should not be applied randomly as double escaping might produce a url (or any kind of content) which do not match the intended url. Escaping should be applied only before output. Therefor the context is more important then the specific function that calculates the URL. </p>\n\n<p>In your example, the first snippet just enqueues the URL and do not output it. The responsibility for escaping is delegated further into the wordpress stack to the code that actually output it, and that is the reason it is not escaped.</p>\n\n<p>The second snippet does the output and that is why the url is being escaped.</p>\n\n<p>So how do you know when you should <strong>not</strong> escape? Hopefully somewhere in the future the documentation of wordpress APIs will include that information, but for now either follow the full code path until the actual output, or test your theme under \"funny\" urls</p>\n"
}
] |
2016/12/24
|
[
"https://wordpress.stackexchange.com/questions/250304",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17937/"
] |
Should `get_template_directory_uri()` be escaped using `esc_url()`?
I ask because taking an example from the default theme Twenty Fifteen the same function is used in two different places but only in one is it escaped.
```
wp_enqueue_style( 'twentyfifteen-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentyfifteen-style' ), '20141010' );
```
-
```
<script src="<?php echo esc_url( get_template_directory_uri() ); ?>/js/html5.js"></script>
```
I would say that that `get_template_directory_uri()` does not need to be generated as the URL cannot be manipulated externally.
|
In that function we find a hook:
```
return apply_filters(
'template_directory_uri',
$template_dir_uri,
$template,
$theme_root_uri
);
```
So, yes, the URI can be changed by plugins, and you should escape its returned value.
The same principle applies to all WordPress URI functions, like `get_home_url()`, `get_site_url()` and so on. Keep in mind that there are not only good plugin developers out there. Some make mistakes, maybe just very small ones that happen only in some circumstances.
In case of `wp_enqueue_style()`, WordPress **does** escape the URL by default. But that is a wrapper for the **global** `WP_Styles` instance, and this in turn [can be replaced easily](https://wordpress.stackexchange.com/a/108364/73) – even with a less safe version. That's not very likely, but you should be aware of this possibility.
Unfortunately, WP itself doesn't follow the *better safe than sorry* directive. It doesn't even escape translations. My advice is not to look at the core themes for best practices. Always look at the source of the data and see if it can be compromised.
|
250,308 |
<p>I do have an post/page where the shortcode "question" occurs many times.
What is the best way to get an array of all the "question" shortcodes with their related parms?</p>
<pre><code>[question a=1 b=2 c=3 ]
[question b=2 c=3 ]
[question a=1 b=2 ]
[question]
</code></pre>
|
[
{
"answer_id": 250312,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 2,
"selected": true,
"text": "<pre><code>function wpse250308_get_questions() {\n global $post;\n if ( preg_match_all('/\\[question(.*?)\\]/', $post->post_content, $questions ) ) {\n $questions = array_key_exists( 1 , $questions) ? $questions[1] : array();\n // $questions will contain the array of the question shortcodes\n //Do your stuff\n }\n} \n</code></pre>\n\n<p><code>$post</code> isn't available before <code>wp</code>. So, you have to hook on it or actions that fires later.</p>\n"
},
{
"answer_id": 400839,
"author": "BernhardWebstudio",
"author_id": 217482,
"author_profile": "https://wordpress.stackexchange.com/users/217482",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use the regular expression provided by WordPress itself using <a href=\"https://developer.wordpress.org/reference/functions/get_shortcode_regex/\" rel=\"nofollow noreferrer\"><code>get_shortcode_regex</code></a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpse250308_get_questions() {\n global $post;\n if ( preg_match_all(get_shortcode_regex('question'), $post->post_content, $questions ) ) {\n $questions = array_key_exists( 1 , $questions) ? $questions[1] : array();\n // $questions will contain the array of the question shortcodes\n // but also, get_shortcode_regex returns a regex that provides some useful capture groups:\n // the get_shortcode_regex from WP provides the matches:\n // 1 – An extra [ to allow for escaping shortcodes with double [[]] \n // 2 – The shortcode name \n // 3 – The shortcode argument list \n // 4 – The self closing / \n // 5 – The content of a shortcode when it wraps some content. \n // 6 – An extra ] to allow for escaping shortcodes with double [[]]\n //Do your stuff\n }\n} \n</code></pre>\n"
}
] |
2016/12/24
|
[
"https://wordpress.stackexchange.com/questions/250308",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109145/"
] |
I do have an post/page where the shortcode "question" occurs many times.
What is the best way to get an array of all the "question" shortcodes with their related parms?
```
[question a=1 b=2 c=3 ]
[question b=2 c=3 ]
[question a=1 b=2 ]
[question]
```
|
```
function wpse250308_get_questions() {
global $post;
if ( preg_match_all('/\[question(.*?)\]/', $post->post_content, $questions ) ) {
$questions = array_key_exists( 1 , $questions) ? $questions[1] : array();
// $questions will contain the array of the question shortcodes
//Do your stuff
}
}
```
`$post` isn't available before `wp`. So, you have to hook on it or actions that fires later.
|
250,349 |
<p>I tried to remove Menus from WordPress customizer (see image)
<a href="https://i.stack.imgur.com/JwOz6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JwOz6.png" alt="enter image description here"></a></p>
<p>I tried the following code on functions.php file and every section was removed except Menus </p>
<pre><code> //Theme customizer
function mytheme_customize_register( $wp_customize ) {
//All our sections, settings, and controls will be added here
$wp_customize->remove_section( 'title_tagline');
$wp_customize->remove_section( 'colors');
$wp_customize->remove_section( 'header_image');
$wp_customize->remove_section( 'background_image');
$wp_customize->remove_section( 'menus');
$wp_customize->remove_section( 'static_front_page');
$wp_customize->remove_section( 'custom_css');
}
add_action( 'customize_register', 'mytheme_customize_register' );
</code></pre>
<p>I even tried </p>
<pre><code>$wp_customize->remove_panel( 'menus');
</code></pre>
<p>but didn't worked i m'i missing something here .appreciate any help on this thanks in advance.</p>
|
[
{
"answer_id": 250356,
"author": "mxUser127",
"author_id": 25525,
"author_profile": "https://wordpress.stackexchange.com/users/25525",
"pm_score": -1,
"selected": false,
"text": "<p>Edit files in admin directory on your server. Even though you may find a plugin for this job. This will help you since it will have a UI and will not restore your menu when updating your wordpress or theme.</p>\n"
},
{
"answer_id": 250368,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 3,
"selected": false,
"text": "<p>The correct way to disable nav menus in the customizer is via the <code>customize_loaded_components</code> filter as documented on its <a href=\"https://developer.wordpress.org/reference/hooks/customize_loaded_components/#comment-1005\" rel=\"noreferrer\">hook reference page</a>:</p>\n\n<pre><code>/**\n * Removes the core 'Menus' panel from the Customizer.\n *\n * @param array $components Core Customizer components list.\n * @return array (Maybe) modified components list.\n */\nfunction wpdocs_remove_nav_menus_panel( $components ) {\n $i = array_search( 'nav_menus', $components );\n if ( false !== $i ) {\n unset( $components[ $i ] );\n }\n return $components;\n}\nadd_filter( 'customize_loaded_components', 'wpdocs_remove_nav_menus_panel' );\n</code></pre>\n\n<p><strong>Important:</strong> this filter has to be added in a plugin since it has to be added before the <code>setup_theme</code> action, which fires just before a theme's <code>functions.php</code> is loaded.</p>\n\n<p>For more information, see these Trac tickets:</p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/33552\" rel=\"noreferrer\">#33552</a>: Facilitate plugins to override Customizer features</li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/37003\" rel=\"noreferrer\">#37003</a>: Removing <code>menus</code> support for a theme doesn't remove Menus section in Customizer</li>\n</ul>\n\n<p>On a related note, for code that resets the customizer to a blank slate so you can add just your own items, see <a href=\"https://make.xwp.co/2016/09/11/resetting-the-customizer-to-a-blank-slate/\" rel=\"noreferrer\">Resetting the Customizer to a Blank Slate</a>.</p>\n"
},
{
"answer_id": 250372,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 4,
"selected": true,
"text": "<p>Try <strong>nav_menus</strong> instead of <strong>menus</strong> with <code>remove_panel()</code></p>\n\n<pre><code>function mytheme_customize_register( $wp_customize ) {\n //All our sections, settings, and controls will be added here\n\n $wp_customize->remove_section( 'title_tagline');\n $wp_customize->remove_section( 'colors');\n $wp_customize->remove_section( 'header_image');\n $wp_customize->remove_section( 'background_image');\n $wp_customize->remove_panel( 'nav_menus');\n $wp_customize->remove_section( 'static_front_page');\n $wp_customize->remove_section( 'custom_css');\n\n}\nadd_action( 'customize_register', 'mytheme_customize_register',50 );\n</code></pre>\n\n<p>Hope this will helps you.</p>\n\n<p>Thank you!</p>\n"
}
] |
2016/12/25
|
[
"https://wordpress.stackexchange.com/questions/250349",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100679/"
] |
I tried to remove Menus from WordPress customizer (see image)
[](https://i.stack.imgur.com/JwOz6.png)
I tried the following code on functions.php file and every section was removed except Menus
```
//Theme customizer
function mytheme_customize_register( $wp_customize ) {
//All our sections, settings, and controls will be added here
$wp_customize->remove_section( 'title_tagline');
$wp_customize->remove_section( 'colors');
$wp_customize->remove_section( 'header_image');
$wp_customize->remove_section( 'background_image');
$wp_customize->remove_section( 'menus');
$wp_customize->remove_section( 'static_front_page');
$wp_customize->remove_section( 'custom_css');
}
add_action( 'customize_register', 'mytheme_customize_register' );
```
I even tried
```
$wp_customize->remove_panel( 'menus');
```
but didn't worked i m'i missing something here .appreciate any help on this thanks in advance.
|
Try **nav\_menus** instead of **menus** with `remove_panel()`
```
function mytheme_customize_register( $wp_customize ) {
//All our sections, settings, and controls will be added here
$wp_customize->remove_section( 'title_tagline');
$wp_customize->remove_section( 'colors');
$wp_customize->remove_section( 'header_image');
$wp_customize->remove_section( 'background_image');
$wp_customize->remove_panel( 'nav_menus');
$wp_customize->remove_section( 'static_front_page');
$wp_customize->remove_section( 'custom_css');
}
add_action( 'customize_register', 'mytheme_customize_register',50 );
```
Hope this will helps you.
Thank you!
|
250,370 |
<p>I am building a site using a custom WP theme, and I have been using:</p>
<pre><code><?php include('header-bar.php'); ?>
</code></pre>
<p>in order to include a navigation bar on each page. I intentionally didn't put the navigation in the header.php file because I don't need it on every page.</p>
<p>That bit of code is working fine in certain places, but failing in others.</p>
<p>It works in this scenario:</p>
<pre><code><?php get_header(); ?>
<div class='main-content'>
<?php include('header-bar.php'); ?>
<div class='container'>
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; endif;
?>
</div>
</div>
<?php get_footer(); ?>
</code></pre>
<p>but it mysteriously fails in this scenario:</p>
<pre><code><?php
/*
Template Name: Contact
*/
?>
<?php get_header(); ?>
<div class='main-content'>
<?php include('header-bar.php'); ?>
<div class='container'>
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; endif;
?>
</div>
</div>
<?php get_footer(); ?>
</code></pre>
<p>In this second scenario, the page displays properly, except for a the 'header-bar.php' code which is nowhere to be found. The change that I am making that seemingly 'breaks' this line of code is by adding the template name. Can anyone offer some insight into why this may be? I'm baffled.</p>
<p>Thanks in advance! CPR</p>
|
[
{
"answer_id": 250371,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 3,
"selected": true,
"text": "<p>Hello CandyPaintedRIMS,</p>\n<p>Please try <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">get_template_part()</a> function to include any file into your custom template.</p>\n<p><strong>Your code:</strong></p>\n<pre><code><?php include('header-bar.php'); ?>\n</code></pre>\n<p><strong>It should be replaced with:</strong></p>\n<pre><code><?php get_template_part( 'header-bar' ); // include header-bar.php ?>\n</code></pre>\n<p>Hope this will helps you.</p>\n<p>Thank you</p>\n"
},
{
"answer_id": 250374,
"author": "Tunji",
"author_id": 54764,
"author_profile": "https://wordpress.stackexchange.com/users/54764",
"pm_score": 1,
"selected": false,
"text": "<p>For the header, you should use the <strong><a href=\"https://developer.wordpress.org/reference/functions/get_header/\" rel=\"nofollow noreferrer\"><code>get_header</code></a></strong> function.</p>\n\n<p><strong>Your code:</strong></p>\n\n<pre><code><?php include('header-bar.php'); ?>\n</code></pre>\n\n<p><strong>Should be replace with:</strong></p>\n\n<pre><code><?php get_header( 'bar' ); ?>\n</code></pre>\n\n<p>The <a href=\"https://developer.wordpress.org/reference/functions/get_header/\" rel=\"nofollow noreferrer\"><strong>get_header</strong></a> function uses <a href=\"https://developer.wordpress.org/reference/functions/locate_template/\" rel=\"nofollow noreferrer\"><strong>locate_template</strong></a> which:</p>\n\n<blockquote>\n <p>Searches in the STYLESHEETPATH before TEMPLATEPATH and\n wp-includes/theme-compat so that themes which inherit from a parent\n theme can just overload one file.</p>\n</blockquote>\n\n<p>and also has a fallback to use the default <strong>header.php</strong> file in any situation the specified header can't be found.</p>\n"
}
] |
2016/12/26
|
[
"https://wordpress.stackexchange.com/questions/250370",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101243/"
] |
I am building a site using a custom WP theme, and I have been using:
```
<?php include('header-bar.php'); ?>
```
in order to include a navigation bar on each page. I intentionally didn't put the navigation in the header.php file because I don't need it on every page.
That bit of code is working fine in certain places, but failing in others.
It works in this scenario:
```
<?php get_header(); ?>
<div class='main-content'>
<?php include('header-bar.php'); ?>
<div class='container'>
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; endif;
?>
</div>
</div>
<?php get_footer(); ?>
```
but it mysteriously fails in this scenario:
```
<?php
/*
Template Name: Contact
*/
?>
<?php get_header(); ?>
<div class='main-content'>
<?php include('header-bar.php'); ?>
<div class='container'>
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile; endif;
?>
</div>
</div>
<?php get_footer(); ?>
```
In this second scenario, the page displays properly, except for a the 'header-bar.php' code which is nowhere to be found. The change that I am making that seemingly 'breaks' this line of code is by adding the template name. Can anyone offer some insight into why this may be? I'm baffled.
Thanks in advance! CPR
|
Hello CandyPaintedRIMS,
Please try [get\_template\_part()](https://developer.wordpress.org/reference/functions/get_template_part/) function to include any file into your custom template.
**Your code:**
```
<?php include('header-bar.php'); ?>
```
**It should be replaced with:**
```
<?php get_template_part( 'header-bar' ); // include header-bar.php ?>
```
Hope this will helps you.
Thank you
|
250,376 |
<p>I'm building a phone numbers directory website. Using <code>wp_insert_post()</code> visitors are allowed to add phone numbers without having to register or log in.
There's a custom post type called "numbers" and phone numbers are stored in custom posts' meta values. Here's the code:</p>
<p><code>$post_id = wp_insert_post(array (
'post_type' => 'numbers',
'post_title' => $name,
'post_content' => $details,
'post_status' => 'draft',
'tax_input' => $custom_tax,
));
if ($post_id) {
// insert post meta
add_post_meta($post_id, 'number', $number);
}</code></p>
<p>I don't want my users to add the numbers that have already been added before. I need to somehow check if the entered phone number already exists in any post's meta value or not.</p>
<p>If number already exists in database, user shouldn't be allowed to add it.</p>
|
[
{
"answer_id": 250380,
"author": "Sofiane Achouba",
"author_id": 92790,
"author_profile": "https://wordpress.stackexchange.com/users/92790",
"pm_score": 1,
"selected": false,
"text": "<p>Hi you can do it like that:</p>\n\n<pre><code>$post_id = wp_insert_post(array (\n 'post_type' => 'numbers',\n 'post_title' => $name,\n 'post_content' => $details,\n 'post_status' => 'draft',\n 'tax_input' => $custom_tax,\n ));\n\nif ($post_id) {\n $args = array(\n 'post_type' => 'numbers',\n 'meta_query' => array(\n array(\n 'key' => 'number',\n 'value' => $number\n )\n ),\n 'fields' => 'ids'\n );\n // perform the query\n $number_query = new WP_Query( $args );\n\n $number_ids = $number_query->posts;\n\n // add number if the meta-key-value-pair does not exist in another post\n if ( empty( $number_ids ) ) {\n add_post_meta($post_id, 'number', $number);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 250384,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 3,
"selected": true,
"text": "<p>Try below code.</p>\n\n<pre><code>$args = array(\n 'fields' => 'ids',\n 'post_type' => 'numbers',\n 'meta_query' => array(\n array(\n 'key' => 'number',\n 'value' => $number\n )\n )\n );\n $my_query = new WP_Query( $args );\n if( empty($my_query->have_posts()) ) {\n $post_id = wp_insert_post(array (\n 'post_type' => 'numbers',\n 'post_title' => $name,\n 'post_content' => $details,\n 'post_status' => 'draft',\n 'tax_input' => $custom_tax,\n ));\n if ($post_id) {\n // insert post meta\n add_post_meta($post_id, 'number', $number);\n }\n }\n</code></pre>\n\n<p>If there is same number in postmeta it will not allow to create post and post meta.</p>\n\n<p>Hope this will helps you.</p>\n"
}
] |
2016/12/26
|
[
"https://wordpress.stackexchange.com/questions/250376",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105471/"
] |
I'm building a phone numbers directory website. Using `wp_insert_post()` visitors are allowed to add phone numbers without having to register or log in.
There's a custom post type called "numbers" and phone numbers are stored in custom posts' meta values. Here's the code:
`$post_id = wp_insert_post(array (
'post_type' => 'numbers',
'post_title' => $name,
'post_content' => $details,
'post_status' => 'draft',
'tax_input' => $custom_tax,
));
if ($post_id) {
// insert post meta
add_post_meta($post_id, 'number', $number);
}`
I don't want my users to add the numbers that have already been added before. I need to somehow check if the entered phone number already exists in any post's meta value or not.
If number already exists in database, user shouldn't be allowed to add it.
|
Try below code.
```
$args = array(
'fields' => 'ids',
'post_type' => 'numbers',
'meta_query' => array(
array(
'key' => 'number',
'value' => $number
)
)
);
$my_query = new WP_Query( $args );
if( empty($my_query->have_posts()) ) {
$post_id = wp_insert_post(array (
'post_type' => 'numbers',
'post_title' => $name,
'post_content' => $details,
'post_status' => 'draft',
'tax_input' => $custom_tax,
));
if ($post_id) {
// insert post meta
add_post_meta($post_id, 'number', $number);
}
}
```
If there is same number in postmeta it will not allow to create post and post meta.
Hope this will helps you.
|
250,379 |
<p>Im in the midst of customizing WooCommerce checkout, adding a dropdown field which get user's meta keys and show as select option in the checkout page. I also managed to save the selected option after checkout into the order. However, the option is displaying as an integer instead of text in the custom field.</p>
<p>The following codes are my development, I hope someone can guide me out.
<a href="https://i.stack.imgur.com/JIqqP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JIqqP.jpg" alt="dropdown"></a></p>
<p><a href="https://i.stack.imgur.com/789Tg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/789Tg.jpg" alt="Custom Field Value"></a></p>
<p>Retrieving user meta keys and display as dropdown options</p>
<pre><code>add_action('woocommerce_after_order_notes', 'wps_add_select_checkout_field');
function wps_add_select_checkout_field( $checkout ) {
$user_id = get_current_user_id();
$vessel_one = get_user_meta( $user_id, 'vessel_one', true );
$vessel_two = get_user_meta( $user_id, 'vessel_two', true );
$vessel_three = get_user_meta( $user_id, 'vessel_three', true );
$vessel_four = get_user_meta( $user_id, 'vessel_four', true );
$vessel_five = get_user_meta( $user_id, 'vessel_five', true );
woocommerce_form_field( 'order_vessel', array(
'type' => 'select',
'class' => array( 'wps-drop' ),
'label' => __( 'Select a Vessel' ),
'options' => array( $vessel_one, $vessel_two, $vessel_three, $vessel_four, $vessel_five )
),
$checkout->get_value( 'order_vessel' ));
}
</code></pre>
<p>Save the value into custom field on the order</p>
<pre><code>add_action('woocommerce_checkout_update_order_meta', 'wps_select_checkout_field_update_order_meta');
function wps_select_checkout_field_update_order_meta( $order_id ) {
if ($_POST['order_vessel']) update_post_meta( $order_id, 'order_vessel', esc_attr($_POST['order_vessel']));
}
</code></pre>
<p>I hope someone could show me how can I save the value as it is and not converted into an integer. Thank you very much in advance.</p>
|
[
{
"answer_id": 250380,
"author": "Sofiane Achouba",
"author_id": 92790,
"author_profile": "https://wordpress.stackexchange.com/users/92790",
"pm_score": 1,
"selected": false,
"text": "<p>Hi you can do it like that:</p>\n\n<pre><code>$post_id = wp_insert_post(array (\n 'post_type' => 'numbers',\n 'post_title' => $name,\n 'post_content' => $details,\n 'post_status' => 'draft',\n 'tax_input' => $custom_tax,\n ));\n\nif ($post_id) {\n $args = array(\n 'post_type' => 'numbers',\n 'meta_query' => array(\n array(\n 'key' => 'number',\n 'value' => $number\n )\n ),\n 'fields' => 'ids'\n );\n // perform the query\n $number_query = new WP_Query( $args );\n\n $number_ids = $number_query->posts;\n\n // add number if the meta-key-value-pair does not exist in another post\n if ( empty( $number_ids ) ) {\n add_post_meta($post_id, 'number', $number);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 250384,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 3,
"selected": true,
"text": "<p>Try below code.</p>\n\n<pre><code>$args = array(\n 'fields' => 'ids',\n 'post_type' => 'numbers',\n 'meta_query' => array(\n array(\n 'key' => 'number',\n 'value' => $number\n )\n )\n );\n $my_query = new WP_Query( $args );\n if( empty($my_query->have_posts()) ) {\n $post_id = wp_insert_post(array (\n 'post_type' => 'numbers',\n 'post_title' => $name,\n 'post_content' => $details,\n 'post_status' => 'draft',\n 'tax_input' => $custom_tax,\n ));\n if ($post_id) {\n // insert post meta\n add_post_meta($post_id, 'number', $number);\n }\n }\n</code></pre>\n\n<p>If there is same number in postmeta it will not allow to create post and post meta.</p>\n\n<p>Hope this will helps you.</p>\n"
}
] |
2016/12/26
|
[
"https://wordpress.stackexchange.com/questions/250379",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109645/"
] |
Im in the midst of customizing WooCommerce checkout, adding a dropdown field which get user's meta keys and show as select option in the checkout page. I also managed to save the selected option after checkout into the order. However, the option is displaying as an integer instead of text in the custom field.
The following codes are my development, I hope someone can guide me out.
[](https://i.stack.imgur.com/JIqqP.jpg)
[](https://i.stack.imgur.com/789Tg.jpg)
Retrieving user meta keys and display as dropdown options
```
add_action('woocommerce_after_order_notes', 'wps_add_select_checkout_field');
function wps_add_select_checkout_field( $checkout ) {
$user_id = get_current_user_id();
$vessel_one = get_user_meta( $user_id, 'vessel_one', true );
$vessel_two = get_user_meta( $user_id, 'vessel_two', true );
$vessel_three = get_user_meta( $user_id, 'vessel_three', true );
$vessel_four = get_user_meta( $user_id, 'vessel_four', true );
$vessel_five = get_user_meta( $user_id, 'vessel_five', true );
woocommerce_form_field( 'order_vessel', array(
'type' => 'select',
'class' => array( 'wps-drop' ),
'label' => __( 'Select a Vessel' ),
'options' => array( $vessel_one, $vessel_two, $vessel_three, $vessel_four, $vessel_five )
),
$checkout->get_value( 'order_vessel' ));
}
```
Save the value into custom field on the order
```
add_action('woocommerce_checkout_update_order_meta', 'wps_select_checkout_field_update_order_meta');
function wps_select_checkout_field_update_order_meta( $order_id ) {
if ($_POST['order_vessel']) update_post_meta( $order_id, 'order_vessel', esc_attr($_POST['order_vessel']));
}
```
I hope someone could show me how can I save the value as it is and not converted into an integer. Thank you very much in advance.
|
Try below code.
```
$args = array(
'fields' => 'ids',
'post_type' => 'numbers',
'meta_query' => array(
array(
'key' => 'number',
'value' => $number
)
)
);
$my_query = new WP_Query( $args );
if( empty($my_query->have_posts()) ) {
$post_id = wp_insert_post(array (
'post_type' => 'numbers',
'post_title' => $name,
'post_content' => $details,
'post_status' => 'draft',
'tax_input' => $custom_tax,
));
if ($post_id) {
// insert post meta
add_post_meta($post_id, 'number', $number);
}
}
```
If there is same number in postmeta it will not allow to create post and post meta.
Hope this will helps you.
|
250,403 |
<p>Looking to discover how to alter my content.php code to add the thumbnail image of the specific posts to my search results located here for example:</p>
<p><a href="https://divesummit.com/?s=suunto&submit=Search" rel="nofollow noreferrer">https://divesummit.com/?s=suunto&submit=Search</a></p>
<p>I would like a thumbnail of the featured post’s image listed along with the smaller blurb of the post in the search results.</p>
<pre><code> <?php get_template_part( 'content', get_post_format() ); ?>
</code></pre>
<p>by somehow changing content.php I can have it include a small thumbnail along with each search result. My theme already has thumb support I just need help implementing it.</p>
<p>Any help on doing this would be appreciated.</p>
<p>PS. I do have a child theme installed</p>
|
[
{
"answer_id": 250399,
"author": "Jami Gibbs",
"author_id": 75524,
"author_profile": "https://wordpress.stackexchange.com/users/75524",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like server response time and stylesheet loading are causing the greatest delay:</p>\n\n<p><a href=\"https://i.stack.imgur.com/z0aag.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/z0aag.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/qam7s.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qam7s.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can measure the network performance of your site yourself using the Network panel in Chrome: Right click > Inspect > Network (refresh the page to load details)</p>\n"
},
{
"answer_id": 250465,
"author": "Third Essential Designer",
"author_id": 103698,
"author_profile": "https://wordpress.stackexchange.com/users/103698",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-move-javascripts-to-the-bottom-or-footer-in-wordpress/\" rel=\"nofollow noreferrer\">This</a> may help you in reducing your loading time. And speed up your website. I this you should try using some cache plugin.</p>\n"
}
] |
2016/12/26
|
[
"https://wordpress.stackexchange.com/questions/250403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109668/"
] |
Looking to discover how to alter my content.php code to add the thumbnail image of the specific posts to my search results located here for example:
<https://divesummit.com/?s=suunto&submit=Search>
I would like a thumbnail of the featured post’s image listed along with the smaller blurb of the post in the search results.
```
<?php get_template_part( 'content', get_post_format() ); ?>
```
by somehow changing content.php I can have it include a small thumbnail along with each search result. My theme already has thumb support I just need help implementing it.
Any help on doing this would be appreciated.
PS. I do have a child theme installed
|
It looks like server response time and stylesheet loading are causing the greatest delay:
[](https://i.stack.imgur.com/z0aag.png)
[](https://i.stack.imgur.com/qam7s.png)
You can measure the network performance of your site yourself using the Network panel in Chrome: Right click > Inspect > Network (refresh the page to load details)
|
250,427 |
<p>So I'm pretty new at Wordpress development, and I'm a little confused by one thing. After going through and finishing my navigation in my header.php file, I went over to my template for the home page I'm working on. My question is: since the "body" tag is the only place you can write that actually shows up in the browser ("header" tags are for meta data etc), can I have more than one body tag? I read a little into html 5, and it seems there are more tags than just "body" now, but what's the best way to do that? I already have my menus wrapped in and what do I do with the footer, etc? Thanks for any help.</p>
|
[
{
"answer_id": 250461,
"author": "Third Essential Designer",
"author_id": 103698,
"author_profile": "https://wordpress.stackexchange.com/users/103698",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/2913303/6887487\">This</a> may help you regarding having two body tags. <a href=\"https://developer.wordpress.org/reference/functions/is_front_page/\" rel=\"nofollow noreferrer\">is_front_page()</a> will help you to echo body tag conditionally... either in header/footer.</p>\n"
},
{
"answer_id": 250471,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 1,
"selected": false,
"text": "<p>Structure your theme so you start the <code><body></code> in the header and you close the <code></body></code> in the footer (same thing for the <code><html></code> tag):</p>\n\n<p>header.php</p>\n\n<pre><code><html>\n...header content\n<body> <!--- body is started in the header, used on every page -->\n</code></pre>\n\n<p>index.php, page.php, single.php, home.php - etc</p>\n\n<pre><code>...content\n</code></pre>\n\n<p>footer.php</p>\n\n<pre><code>...footer content\n</body> <!-- body is closed in the footer, also used on every page -->\n</html>\n</code></pre>\n"
}
] |
2016/12/27
|
[
"https://wordpress.stackexchange.com/questions/250427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108586/"
] |
So I'm pretty new at Wordpress development, and I'm a little confused by one thing. After going through and finishing my navigation in my header.php file, I went over to my template for the home page I'm working on. My question is: since the "body" tag is the only place you can write that actually shows up in the browser ("header" tags are for meta data etc), can I have more than one body tag? I read a little into html 5, and it seems there are more tags than just "body" now, but what's the best way to do that? I already have my menus wrapped in and what do I do with the footer, etc? Thanks for any help.
|
Structure your theme so you start the `<body>` in the header and you close the `</body>` in the footer (same thing for the `<html>` tag):
header.php
```
<html>
...header content
<body> <!--- body is started in the header, used on every page -->
```
index.php, page.php, single.php, home.php - etc
```
...content
```
footer.php
```
...footer content
</body> <!-- body is closed in the footer, also used on every page -->
</html>
```
|
250,452 |
<p>Here is my custom type post code. I want to add the meta box in there...</p>
<pre><code>function events_cust(){
$label = array(
'name' => _x('Events'),
'singular_name' => _x('events'),
'menu_name' => __('Events'),
'add_new' => __('Add Event'),
'add_new_item' => __ ('Add New Event'),
'all_item' => __('All Event'),
'edit_item' => __('Edit Event'),
'new_item' => __('New Event'),
'view_item' => __('View Event'),
'update_item' => __('update Event'),
'search_item' => __('Search Event')
);
$attr = array(
'label' => __('Events'),
'description' => __('Event'),
'labels' => $label,
'supports' => array('title','editor','thumbnail'),
'taxonomies' => array('genres'),
'hiecrarhical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_adim_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type('events-lists',$attr);
}
add_action( 'init', 'events_cust', 0 );
add_action('add_meta_boxes','create_events_metaboxes');
function create_events_metaboxes(){
add_meta_box('events-meta-box','Events Details','show_events_metaboxes','events-lists','normal','hight');
}
function show_events_metaboxes(){
echo 'Hello Meta box';
}
</code></pre>
<p>What's wrong with us.</p>
|
[
{
"answer_id": 250456,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 1,
"selected": false,
"text": "<p>Try below code.</p>\n\n<pre><code>add_action('add_meta_boxes','create_events_metaboxes'); \nfunction create_events_metaboxes() { \n add_meta_box('events-meta-box','Events Details','show_events_metaboxes','events-lists'); \n}\n\nfunction show_events_metaboxes($post){ echo 'Hello Meta box'; }\n</code></pre>\n\n<p>Hope this will helps you.</p>\n\n<p>Refer from <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">add_meta_box</a></p>\n"
},
{
"answer_id": 250457,
"author": "Third Essential Designer",
"author_id": 103698,
"author_profile": "https://wordpress.stackexchange.com/users/103698",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://wordpress.org/plugins/advanced-custom-fields/\" rel=\"nofollow noreferrer\">ACF</a> may help in your farther run. Try it if you need meta boxes more organised.</p>\n"
},
{
"answer_id": 250486,
"author": "B.M.Rafiul Alam",
"author_id": 107673,
"author_profile": "https://wordpress.stackexchange.com/users/107673",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code> function event_custom_meta_boxes( $post_type, $post ) {\n add_meta_box( \n 'my-meta-box',\n __( 'My Meta Box' ),\n 'render_my_meta_box',\n 'post', //post type, event, product etc. \n 'normal',\n 'default'\n );\n }\n add_action( 'add_meta_boxes', 'event_custom_meta_boxes', 10, 2 );\n\n function render_my_meta_box(){\n echo \"Hello World!\";\n }\n</code></pre>\n\n<p>for more reference: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes</a></p>\n"
}
] |
2016/12/27
|
[
"https://wordpress.stackexchange.com/questions/250452",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109713/"
] |
Here is my custom type post code. I want to add the meta box in there...
```
function events_cust(){
$label = array(
'name' => _x('Events'),
'singular_name' => _x('events'),
'menu_name' => __('Events'),
'add_new' => __('Add Event'),
'add_new_item' => __ ('Add New Event'),
'all_item' => __('All Event'),
'edit_item' => __('Edit Event'),
'new_item' => __('New Event'),
'view_item' => __('View Event'),
'update_item' => __('update Event'),
'search_item' => __('Search Event')
);
$attr = array(
'label' => __('Events'),
'description' => __('Event'),
'labels' => $label,
'supports' => array('title','editor','thumbnail'),
'taxonomies' => array('genres'),
'hiecrarhical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_adim_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type('events-lists',$attr);
}
add_action( 'init', 'events_cust', 0 );
add_action('add_meta_boxes','create_events_metaboxes');
function create_events_metaboxes(){
add_meta_box('events-meta-box','Events Details','show_events_metaboxes','events-lists','normal','hight');
}
function show_events_metaboxes(){
echo 'Hello Meta box';
}
```
What's wrong with us.
|
Try below code.
```
add_action('add_meta_boxes','create_events_metaboxes');
function create_events_metaboxes() {
add_meta_box('events-meta-box','Events Details','show_events_metaboxes','events-lists');
}
function show_events_metaboxes($post){ echo 'Hello Meta box'; }
```
Hope this will helps you.
Refer from [add\_meta\_box](https://developer.wordpress.org/reference/functions/add_meta_box/)
|
250,478 |
<p>After installing wordpress importer from Tools option in wordpress, when I try to activate it, it gives fatal error.</p>
<p><img src="https://i.imgur.com/0Ky3XqU.png" alt="Screenshot"></p>
<p>The relevant php code:</p>
<pre><code>class WXR_Parser {
function parse( $file ) {
// Attempt to use proper XML parsers first
if ( extension_loaded( 'simplexml' ) ) {
$parser = new WXR_Parser_SimpleXML;
$result = $parser->parse( $file );
// If SimpleXML succeeds or this is an invalid WXR file then return the results
if ( ! is_wp_error( $result ) || 'SimpleXML_parse_error' != $result->get_error_code() )
return $result;
} else if ( extension_loaded( 'xml' ) ) {
$parser = new WXR_Parser_XML;
$result = $parser->parse( $file );
// If XMLParser succeeds or this is an invalid WXR file then return the results
if ( ! is_wp_error( $result ) || 'XML_parse_error' != $result->get_error_code() )
return $result;
}
// We have a malformed XML file, so display the error and fallthrough to regex
if ( isset($result) && defined('IMPORT_DEBUG') && IMPORT_DEBUG ) {
echo '<pre>';
if ( 'SimpleXML_parse_error' == $result->get_error_code() ) {
foreach ( $result->get_error_data() as $error )
echo $error->line . ':' . $error->column . ' ' . esc_html( $error->message ) . "\n";
} else if ( 'XML_parse_error' == $result->get_error_code() ) {
$error = $result->get_error_data();
echo $error[0] . ':' . $error[1] . ' ' . esc_html( $error[2] );
}
echo '</pre>';
echo '<p><strong>' . __( 'There was an error when reading this WXR file', 'wordpress-importer' ) . '</strong><br />';
echo __( 'Details are shown above. The importer will now try again with a different parser...', 'wordpress-importer' ) . '</p>';
}
// use regular expressions if nothing else available or this is bad XML
$parser = new WXR_Parser_Regex;
return $parser->parse( $file );
}
}
</code></pre>
|
[
{
"answer_id": 250480,
"author": "Jami Gibbs",
"author_id": 75524,
"author_profile": "https://wordpress.stackexchange.com/users/75524",
"pm_score": 3,
"selected": true,
"text": "<p>That error suggests that the <code>WXR_Parser</code> class is already \"running\" or declared. It's possible that a theme or another plugin has incorporated that class and did not check if it existed already before initializing. ie. <code>if ( ! class_exists( 'WXR_Parser' ) )</code>.</p>\n\n<p>To locate the source of the conflict, deactivate each <em>theme and plugin</em> one-by-one. You should be left with just a default theme active (ie. TwentyFifteen).</p>\n"
},
{
"answer_id": 250678,
"author": "Meet Shah",
"author_id": 66687,
"author_profile": "https://wordpress.stackexchange.com/users/66687",
"pm_score": 1,
"selected": false,
"text": "<p>This happened with me too.</p>\n\n<p>I did not go to code section for this.</p>\n\n<p>I changed the activated-theme to Twenty-Sixteen and then I tried to activate the plugin and succeed.</p>\n"
},
{
"answer_id": 296187,
"author": "Amar Verma",
"author_id": 138234,
"author_profile": "https://wordpress.stackexchange.com/users/138234",
"pm_score": 0,
"selected": false,
"text": "<p>i had same error with a theme, then I switched to wordpress default theme, then installed the worpress importer.... its installed and working well. then I changed my favourite theme, which is working well.\nThanks.</p>\n"
}
] |
2016/12/27
|
[
"https://wordpress.stackexchange.com/questions/250478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106457/"
] |
After installing wordpress importer from Tools option in wordpress, when I try to activate it, it gives fatal error.

The relevant php code:
```
class WXR_Parser {
function parse( $file ) {
// Attempt to use proper XML parsers first
if ( extension_loaded( 'simplexml' ) ) {
$parser = new WXR_Parser_SimpleXML;
$result = $parser->parse( $file );
// If SimpleXML succeeds or this is an invalid WXR file then return the results
if ( ! is_wp_error( $result ) || 'SimpleXML_parse_error' != $result->get_error_code() )
return $result;
} else if ( extension_loaded( 'xml' ) ) {
$parser = new WXR_Parser_XML;
$result = $parser->parse( $file );
// If XMLParser succeeds or this is an invalid WXR file then return the results
if ( ! is_wp_error( $result ) || 'XML_parse_error' != $result->get_error_code() )
return $result;
}
// We have a malformed XML file, so display the error and fallthrough to regex
if ( isset($result) && defined('IMPORT_DEBUG') && IMPORT_DEBUG ) {
echo '<pre>';
if ( 'SimpleXML_parse_error' == $result->get_error_code() ) {
foreach ( $result->get_error_data() as $error )
echo $error->line . ':' . $error->column . ' ' . esc_html( $error->message ) . "\n";
} else if ( 'XML_parse_error' == $result->get_error_code() ) {
$error = $result->get_error_data();
echo $error[0] . ':' . $error[1] . ' ' . esc_html( $error[2] );
}
echo '</pre>';
echo '<p><strong>' . __( 'There was an error when reading this WXR file', 'wordpress-importer' ) . '</strong><br />';
echo __( 'Details are shown above. The importer will now try again with a different parser...', 'wordpress-importer' ) . '</p>';
}
// use regular expressions if nothing else available or this is bad XML
$parser = new WXR_Parser_Regex;
return $parser->parse( $file );
}
}
```
|
That error suggests that the `WXR_Parser` class is already "running" or declared. It's possible that a theme or another plugin has incorporated that class and did not check if it existed already before initializing. ie. `if ( ! class_exists( 'WXR_Parser' ) )`.
To locate the source of the conflict, deactivate each *theme and plugin* one-by-one. You should be left with just a default theme active (ie. TwentyFifteen).
|
250,485 |
<p>In order to use HTML5 markup for the comment forms, I add the following code snippet to <code>functions.php</code>:</p>
<pre><code>add_theme_support( 'html5', array( 'comment-form' ) );
</code></pre>
<p>However, it disables client side validation on form submit and I get redirected to an error page:</p>
<p><a href="https://i.stack.imgur.com/78Bpq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/78Bpq.png" alt="Error page redirect"></a></p>
<p>Now, if I remove <code>add_theme_support( 'html5', array( 'comment-form' ) );</code> and submit the comment form, I get client side validation:</p>
<p><a href="https://i.stack.imgur.com/NsH4B.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NsH4B.png" alt="Client side validation"></a></p>
<p>Can anybody explain why this is? Is it a bug? Or expected behavior?</p>
<p>I am currently using WordPress 4.7.</p>
|
[
{
"answer_id": 264807,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<p>No, it is not a bug. This is how core handles it. If you look into <code>/wp-includes/comment-template.php</code>, you'll notice, that the only difference in <code><form></code> element, is <code>novalidate</code> attribute added, when <code>current_theme_supports( 'html5', 'comment-form' )</code> is true. But there are other html elements within comment form, which are affected by theme's choice of html5 support. For example:\ninput field for email ( <code>type=\"email\"</code> - html5, <code>type=\"text\"</code> - xhtml ), and input field for url ( <code>type=\"url\"</code> - html5, <code>type=\"text\"</code> - xhtml ).</p>\n\n<p>I would not recommend to remove theme support for html5. WordPress, now, builds our documents with <code><!DOCTYPE html></code>, which means, HTML5. If we do remove support, our document will not validate as correct XTML5.</p>\n\n<p>So, how to deal with this offending <code>novalidate</code> attribute? Simple jQuery script will fix it.</p>\n\n<p>Create file <code>removenovalidate.js</code> and put the code below in it:</p>\n\n<pre><code>jQuery( document ).ready(function($) {\n $('#commentform').removeAttr('novalidate');\n});\n</code></pre>\n\n<p>Save this file to your theme's folder. Add the code below to your theme's <code>functions.php</code>:</p>\n\n<pre><code>function fpw_enqueue_scripts() {\n if ( is_single() ) { \n wp_register_script( 'fpw_remove_novalidate', get_stylesheet_directory_uri() . '/removenovalidate.js', array( 'jquery' ), false, true );\n wp_enqueue_script( 'fpw_remove_novalidate' );\n }\n}\nadd_action('wp_enqueue_scripts', 'fpw_enqueue_scripts', 10 );\n</code></pre>\n\n<p>All done. Your comments form will validate now.</p>\n"
},
{
"answer_id": 311548,
"author": "Programmeur Désespéré",
"author_id": 95142,
"author_profile": "https://wordpress.stackexchange.com/users/95142",
"pm_score": 0,
"selected": false,
"text": "<p>You can remove <code>novalidate</code> attribute with this simple Javascript:</p>\n\n<pre><code><script type=\"text/javascript\">\n var commentForm = document.getElementById('commentform'); \n commentForm.removeAttribute('novalidate');\n</script>\n</code></pre>\n\n<p>No jQuery needed. </p>\n\n<p>You can include the following code to run script just on posts:</p>\n\n<h3>footer.php</h3>\n\n<pre><code><?php if( is_singular() ) : ?>\n <script type=\"text/javascript\">\n var commentForm = document.getElementById('commentform');\n commentForm.removeAttribute('novalidate');\n </script>\n<?php endif; ?>\n</code></pre>\n"
}
] |
2016/12/27
|
[
"https://wordpress.stackexchange.com/questions/250485",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109650/"
] |
In order to use HTML5 markup for the comment forms, I add the following code snippet to `functions.php`:
```
add_theme_support( 'html5', array( 'comment-form' ) );
```
However, it disables client side validation on form submit and I get redirected to an error page:
[](https://i.stack.imgur.com/78Bpq.png)
Now, if I remove `add_theme_support( 'html5', array( 'comment-form' ) );` and submit the comment form, I get client side validation:
[](https://i.stack.imgur.com/NsH4B.png)
Can anybody explain why this is? Is it a bug? Or expected behavior?
I am currently using WordPress 4.7.
|
No, it is not a bug. This is how core handles it. If you look into `/wp-includes/comment-template.php`, you'll notice, that the only difference in `<form>` element, is `novalidate` attribute added, when `current_theme_supports( 'html5', 'comment-form' )` is true. But there are other html elements within comment form, which are affected by theme's choice of html5 support. For example:
input field for email ( `type="email"` - html5, `type="text"` - xhtml ), and input field for url ( `type="url"` - html5, `type="text"` - xhtml ).
I would not recommend to remove theme support for html5. WordPress, now, builds our documents with `<!DOCTYPE html>`, which means, HTML5. If we do remove support, our document will not validate as correct XTML5.
So, how to deal with this offending `novalidate` attribute? Simple jQuery script will fix it.
Create file `removenovalidate.js` and put the code below in it:
```
jQuery( document ).ready(function($) {
$('#commentform').removeAttr('novalidate');
});
```
Save this file to your theme's folder. Add the code below to your theme's `functions.php`:
```
function fpw_enqueue_scripts() {
if ( is_single() ) {
wp_register_script( 'fpw_remove_novalidate', get_stylesheet_directory_uri() . '/removenovalidate.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'fpw_remove_novalidate' );
}
}
add_action('wp_enqueue_scripts', 'fpw_enqueue_scripts', 10 );
```
All done. Your comments form will validate now.
|
250,513 |
<p>I have a problem. I need to list only 2 roles: customer and shop_manager. 1. How can i do that with this script?</p>
<pre><code>add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
global $wp_roles;
echo '<select name="role" class="input">';
foreach ( $wp_roles->roles as $key=>$value ):
echo '<option value="'.$key.'">'.$value['name'].'</option>';
endforeach;
echo '</select>';
}
</code></pre>
|
[
{
"answer_id": 264807,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<p>No, it is not a bug. This is how core handles it. If you look into <code>/wp-includes/comment-template.php</code>, you'll notice, that the only difference in <code><form></code> element, is <code>novalidate</code> attribute added, when <code>current_theme_supports( 'html5', 'comment-form' )</code> is true. But there are other html elements within comment form, which are affected by theme's choice of html5 support. For example:\ninput field for email ( <code>type=\"email\"</code> - html5, <code>type=\"text\"</code> - xhtml ), and input field for url ( <code>type=\"url\"</code> - html5, <code>type=\"text\"</code> - xhtml ).</p>\n\n<p>I would not recommend to remove theme support for html5. WordPress, now, builds our documents with <code><!DOCTYPE html></code>, which means, HTML5. If we do remove support, our document will not validate as correct XTML5.</p>\n\n<p>So, how to deal with this offending <code>novalidate</code> attribute? Simple jQuery script will fix it.</p>\n\n<p>Create file <code>removenovalidate.js</code> and put the code below in it:</p>\n\n<pre><code>jQuery( document ).ready(function($) {\n $('#commentform').removeAttr('novalidate');\n});\n</code></pre>\n\n<p>Save this file to your theme's folder. Add the code below to your theme's <code>functions.php</code>:</p>\n\n<pre><code>function fpw_enqueue_scripts() {\n if ( is_single() ) { \n wp_register_script( 'fpw_remove_novalidate', get_stylesheet_directory_uri() . '/removenovalidate.js', array( 'jquery' ), false, true );\n wp_enqueue_script( 'fpw_remove_novalidate' );\n }\n}\nadd_action('wp_enqueue_scripts', 'fpw_enqueue_scripts', 10 );\n</code></pre>\n\n<p>All done. Your comments form will validate now.</p>\n"
},
{
"answer_id": 311548,
"author": "Programmeur Désespéré",
"author_id": 95142,
"author_profile": "https://wordpress.stackexchange.com/users/95142",
"pm_score": 0,
"selected": false,
"text": "<p>You can remove <code>novalidate</code> attribute with this simple Javascript:</p>\n\n<pre><code><script type=\"text/javascript\">\n var commentForm = document.getElementById('commentform'); \n commentForm.removeAttribute('novalidate');\n</script>\n</code></pre>\n\n<p>No jQuery needed. </p>\n\n<p>You can include the following code to run script just on posts:</p>\n\n<h3>footer.php</h3>\n\n<pre><code><?php if( is_singular() ) : ?>\n <script type=\"text/javascript\">\n var commentForm = document.getElementById('commentform');\n commentForm.removeAttribute('novalidate');\n </script>\n<?php endif; ?>\n</code></pre>\n"
}
] |
2016/12/27
|
[
"https://wordpress.stackexchange.com/questions/250513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109748/"
] |
I have a problem. I need to list only 2 roles: customer and shop\_manager. 1. How can i do that with this script?
```
add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
global $wp_roles;
echo '<select name="role" class="input">';
foreach ( $wp_roles->roles as $key=>$value ):
echo '<option value="'.$key.'">'.$value['name'].'</option>';
endforeach;
echo '</select>';
}
```
|
No, it is not a bug. This is how core handles it. If you look into `/wp-includes/comment-template.php`, you'll notice, that the only difference in `<form>` element, is `novalidate` attribute added, when `current_theme_supports( 'html5', 'comment-form' )` is true. But there are other html elements within comment form, which are affected by theme's choice of html5 support. For example:
input field for email ( `type="email"` - html5, `type="text"` - xhtml ), and input field for url ( `type="url"` - html5, `type="text"` - xhtml ).
I would not recommend to remove theme support for html5. WordPress, now, builds our documents with `<!DOCTYPE html>`, which means, HTML5. If we do remove support, our document will not validate as correct XTML5.
So, how to deal with this offending `novalidate` attribute? Simple jQuery script will fix it.
Create file `removenovalidate.js` and put the code below in it:
```
jQuery( document ).ready(function($) {
$('#commentform').removeAttr('novalidate');
});
```
Save this file to your theme's folder. Add the code below to your theme's `functions.php`:
```
function fpw_enqueue_scripts() {
if ( is_single() ) {
wp_register_script( 'fpw_remove_novalidate', get_stylesheet_directory_uri() . '/removenovalidate.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'fpw_remove_novalidate' );
}
}
add_action('wp_enqueue_scripts', 'fpw_enqueue_scripts', 10 );
```
All done. Your comments form will validate now.
|
250,521 |
<p>I have an issue reaching my Wordpress login page. <a href="http://www.everydaytherapy.ie/wp-admin" rel="nofollow noreferrer">http://www.everydaytherapy.ie/wp-admin</a>
I am redirected and a drop down menu appears to login in. But not the proper Wordpress login screen (check the URL yourself). I still tried to login but my details didn't work for it. It would just reset. I have tried deleting the .htaccess file, adding the URL's to the config.php file and anything else I could find online. I went into phpMyadmin and the tables seem correct. I deactivated all my plugin's and even my theme and still the same issue.
Any help would be greatly appreciated!</p>
|
[
{
"answer_id": 264807,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<p>No, it is not a bug. This is how core handles it. If you look into <code>/wp-includes/comment-template.php</code>, you'll notice, that the only difference in <code><form></code> element, is <code>novalidate</code> attribute added, when <code>current_theme_supports( 'html5', 'comment-form' )</code> is true. But there are other html elements within comment form, which are affected by theme's choice of html5 support. For example:\ninput field for email ( <code>type=\"email\"</code> - html5, <code>type=\"text\"</code> - xhtml ), and input field for url ( <code>type=\"url\"</code> - html5, <code>type=\"text\"</code> - xhtml ).</p>\n\n<p>I would not recommend to remove theme support for html5. WordPress, now, builds our documents with <code><!DOCTYPE html></code>, which means, HTML5. If we do remove support, our document will not validate as correct XTML5.</p>\n\n<p>So, how to deal with this offending <code>novalidate</code> attribute? Simple jQuery script will fix it.</p>\n\n<p>Create file <code>removenovalidate.js</code> and put the code below in it:</p>\n\n<pre><code>jQuery( document ).ready(function($) {\n $('#commentform').removeAttr('novalidate');\n});\n</code></pre>\n\n<p>Save this file to your theme's folder. Add the code below to your theme's <code>functions.php</code>:</p>\n\n<pre><code>function fpw_enqueue_scripts() {\n if ( is_single() ) { \n wp_register_script( 'fpw_remove_novalidate', get_stylesheet_directory_uri() . '/removenovalidate.js', array( 'jquery' ), false, true );\n wp_enqueue_script( 'fpw_remove_novalidate' );\n }\n}\nadd_action('wp_enqueue_scripts', 'fpw_enqueue_scripts', 10 );\n</code></pre>\n\n<p>All done. Your comments form will validate now.</p>\n"
},
{
"answer_id": 311548,
"author": "Programmeur Désespéré",
"author_id": 95142,
"author_profile": "https://wordpress.stackexchange.com/users/95142",
"pm_score": 0,
"selected": false,
"text": "<p>You can remove <code>novalidate</code> attribute with this simple Javascript:</p>\n\n<pre><code><script type=\"text/javascript\">\n var commentForm = document.getElementById('commentform'); \n commentForm.removeAttribute('novalidate');\n</script>\n</code></pre>\n\n<p>No jQuery needed. </p>\n\n<p>You can include the following code to run script just on posts:</p>\n\n<h3>footer.php</h3>\n\n<pre><code><?php if( is_singular() ) : ?>\n <script type=\"text/javascript\">\n var commentForm = document.getElementById('commentform');\n commentForm.removeAttribute('novalidate');\n </script>\n<?php endif; ?>\n</code></pre>\n"
}
] |
2016/12/28
|
[
"https://wordpress.stackexchange.com/questions/250521",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100619/"
] |
I have an issue reaching my Wordpress login page. <http://www.everydaytherapy.ie/wp-admin>
I am redirected and a drop down menu appears to login in. But not the proper Wordpress login screen (check the URL yourself). I still tried to login but my details didn't work for it. It would just reset. I have tried deleting the .htaccess file, adding the URL's to the config.php file and anything else I could find online. I went into phpMyadmin and the tables seem correct. I deactivated all my plugin's and even my theme and still the same issue.
Any help would be greatly appreciated!
|
No, it is not a bug. This is how core handles it. If you look into `/wp-includes/comment-template.php`, you'll notice, that the only difference in `<form>` element, is `novalidate` attribute added, when `current_theme_supports( 'html5', 'comment-form' )` is true. But there are other html elements within comment form, which are affected by theme's choice of html5 support. For example:
input field for email ( `type="email"` - html5, `type="text"` - xhtml ), and input field for url ( `type="url"` - html5, `type="text"` - xhtml ).
I would not recommend to remove theme support for html5. WordPress, now, builds our documents with `<!DOCTYPE html>`, which means, HTML5. If we do remove support, our document will not validate as correct XTML5.
So, how to deal with this offending `novalidate` attribute? Simple jQuery script will fix it.
Create file `removenovalidate.js` and put the code below in it:
```
jQuery( document ).ready(function($) {
$('#commentform').removeAttr('novalidate');
});
```
Save this file to your theme's folder. Add the code below to your theme's `functions.php`:
```
function fpw_enqueue_scripts() {
if ( is_single() ) {
wp_register_script( 'fpw_remove_novalidate', get_stylesheet_directory_uri() . '/removenovalidate.js', array( 'jquery' ), false, true );
wp_enqueue_script( 'fpw_remove_novalidate' );
}
}
add_action('wp_enqueue_scripts', 'fpw_enqueue_scripts', 10 );
```
All done. Your comments form will validate now.
|
250,529 |
<p>I've finally figured out how the post loop works (very new to coding), and I'm trying to figure out the best way to add a class to individual posts I'm displaying (title, author, etc when I add all of them) in the following code:</p>
<pre><code> $args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo $recent["the_post_thumbnail"];
echo '<ul><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </ul> ';?>
<ul><?php echo $recent["post_excerpt"];?></ul>
<?php
}
wp_reset_query();
?>
<?php
</code></pre>
|
[
{
"answer_id": 250534,
"author": "jetyet47",
"author_id": 91783,
"author_profile": "https://wordpress.stackexchange.com/users/91783",
"pm_score": 2,
"selected": false,
"text": "<p>Not totally clear what you're asking, but post_class is probably your best bet.</p>\n\n<pre><code><?php post_class(); ?>\n</code></pre>\n\n<p>More info: <a href=\"https://codex.wordpress.org/Function_Reference/post_class\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/post_class</a></p>\n"
},
{
"answer_id": 250549,
"author": "Rishabh",
"author_id": 81621,
"author_profile": "https://wordpress.stackexchange.com/users/81621",
"pm_score": 0,
"selected": false,
"text": "<p>If you are showing list of latest post then here is the easier way of it in which you can add classes and DIV as per your wish.</p>\n\n<pre><code>$paged = get_query_var('paged') ? get_query_var('paged') : 1;\n $args = array(\n 'post_type' => 'post', //Post type that you want to show\n 'posts_per_page' => 5, //No. of Pages to show \n 'offset' => 0, //excluding the latest post if any\n 'paged' => $paged //For Pagination\n );\n\n$loop = new WP_Query( $args );\n\nwhile ( $loop->have_posts() ) : $loop->the_post();?>\n <?php /*** Title of Post ***/ ?>\n <h3><a href=\"<?php the_permalink() ?>\" title=\"<?php the_title(); ?>\"><?php the_title();?></a></h3>\n <?php /*** Title of Post ends ***/ ?>\n <?php \n /***** Thumbnail ******/\n the_post_thumbnail(\n array(120, 90), \n array(\n\n 'class' => 'enter_class', //custom class for post thumbnail if any \n 'alt' => 'post thumbnail', //post thumbnail alternate title\n 'title' => 'my custom title' //Title of thumbnail\n )\n );\n/******* Thumbnail Ends ********/\n/*** Post contents/Description ***/\nthe_excerpt();\n/*** Post contents/Description ends ***/\n?> \n<?php \nendwhile;\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>If you want to add div on individual post then you need to add div inside <code>while</code> loop. </p>\n\n<p>If you want to wrap your every post in individual div then add div in <code>while</code> loop in above mentioned code like this</p>\n\n<pre><code><?php while ( $loop->have_posts() ) : $loop->the_post(); ?>\n<div class=\"enter_class_name\">\n <?php\n //Rest of the code in while loop like title,description and thumbnail code will come here.\n ?>\n\n</div>\n</code></pre>\n\n<p><strong>NOTE</strong> Make sure you don't add DIV inside php tags (<code><?php ?></code>). Specify your DIV outside php tags.</p>\n\n<p>And you can also add DIV in parts of post also. For example if you want to add DIV to wrap thumbnail of every posta individually then you can also do that easily.</p>\n\n<p>To do that you have to read all comments in code to understand what code is using to show thumbnail of post and simply wrap that code inside DIV. And your post thumbnail will be enclosed in separate DIV. </p>\n\n<p>In my given code this piece of code inside while loop is responsible for showing post thumbnail</p>\n\n<pre><code><?php \n/***** Thumbnail ******/\nthe_post_thumbnail(\n array(120, 90), \n array(\n\n 'class' => 'enter_class', //custom class for post thumbnail if any \n 'alt' => 'post thumbnail', //post thumbnail alternate title\n 'title' => 'my custom title' //Title of thumbnail\n )\n);\n/******* Thumbnail Ends ********/\n</code></pre>\n\n<p>And to wrap thumbnail inside div, just wrap this code inside div(outside php tags) like this</p>\n\n<pre><code><div class=\"enter_class_name\">\n <?php \n /***** Thumbnail ******/\n the_post_thumbnail(\n array(120, 90), \n array(\n\n 'class' => 'enter_class', //custom class for post thumbnail if any \n 'alt' => 'post thumbnail', //post thumbnail alternate title\n 'title' => 'my custom title' //Title of thumbnail\n )\n );\n /******* Thumbnail Ends ********/\n ?>\n</div>\n</code></pre>\n\n<p>Like this you can also wrap your Title of post or Description of post in separate DIV just by enclosing their respective code in DIV. </p>\n\n<p>BUT make sure to put all DIVs only inside <code>while</code> loop. Only then your posts will get separate DIV. </p>\n\n<p>And it is strongly recommended that you read all comments line attach to the code carefully to understand every line of code is performing what kind of action/activity. This info will help you to add DIV as per your need.</p>\n"
}
] |
2016/12/28
|
[
"https://wordpress.stackexchange.com/questions/250529",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108586/"
] |
I've finally figured out how the post loop works (very new to coding), and I'm trying to figure out the best way to add a class to individual posts I'm displaying (title, author, etc when I add all of them) in the following code:
```
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo $recent["the_post_thumbnail"];
echo '<ul><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </ul> ';?>
<ul><?php echo $recent["post_excerpt"];?></ul>
<?php
}
wp_reset_query();
?>
<?php
```
|
Not totally clear what you're asking, but post\_class is probably your best bet.
```
<?php post_class(); ?>
```
More info: <https://codex.wordpress.org/Function_Reference/post_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.